1

So I have this JavaScript file and I want to globally change a field for the current authenticated user? I have a profile model with a level field:

class Profile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    level = models.IntegerField(default=1)

And for my url I have added the context and got it to log into the targeted JS file

urls.py

def game(request):
    profile = Profile.objects.get(user=request.user) #profile object
    level = profile.level #level context from the profile
    return render(request, 'games/game.html', {'level': level})

game.js:

const data = document.currentScript.dataset;
const level = parseInt(data.level);
console.log(level);


// BOILER PLATE FETCH //
fetch(url, {
    method: "POST",
    credentials: "same-origin",
    headers: {
      "X-Requested-With": "XMLHttpRequest",
      "X-CSRFToken": getCookie("csrftoken"),
    },
    body: JSON.stringify({payload: "data to send"})
  })
  .then(response => response.json())
  .then(data => {
    console.log(data);
  });

and It console logs the level from that, However I want to know Is it possible to ''globally'' edit the level value using that boilerplate fetch down there? or maybe Ajax? My main issue is that I think I could specifically edit the level for the showProfilePage view (maybe) but I would prefer the level to be permanently updated to the desired number. That way it would retain its updated number anywhere I used its context. I just don't even know where to begin. I thought that maybe like the register form in my views.py I could save the profile some way maybe upon success? Am I on the right track? I'm new to Django and don't fully understand POST request with context, I've read the Docs and watched a few videos which is where I got the Idea but If i could just post the result of the level being updated (by one) on the authenticated users view profile than that would be fine. Insight would be much appreciated!

  • You take my answer here as a reference just change the `get` to `post` and in the view update the level you got https://stackoverflow.com/questions/20306981/how-do-i-integrate-ajax-with-django-applications/54607627#54607627 – Ahtisham Aug 16 '23 at 08:09
  • @Ahtisham Okay thanks I appreciate this, However I'm still struggling with what exactly to be pulling and posting since I'm only editing the value/field permently. https://pastebin.com/27nqhJ6W – user19522235 Aug 16 '23 at 21:02

0 Answers0