pythondjango

How to reference/mess with a model in a JS file (Django)


So I have a model Profile with a field level (IntegerField) upon completion I would like to add a number to that field but I'm not sure how to reference it in the JS file. Can I edit a models field in a JS file? I'm new to Django and couldn't find anything in the ''documentation''.

class Profile(models.Model):
    user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
    rpg_class = models.CharField(max_length=100, default='Warrior')
    level = models.IntegerField(default=1)

    def __str__(self):
        return str(self.user) 

Views.py:

profile = self.get_object()
        context['level'] = profile.level
        return context

for now I just want to know if I can do something like this in hte JS file model_name += 1; but I cant figure out how to reference it


Solution

  • It sounds like you are using an external JS file. To get data into there from your template you can do something like this when you include the file. YOu may need to pass your profile PK in as well for later Ajax:

    {% load static %}
    <script src="{% static 'profile.js' %}"
            defer
            data-level="{{ level }}"
            data-pk = "{{ pk }}"
    ></script>
    

    Then in your script you can use:

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

    (hat tip to this article for the method - a good read!

    To update the model itself, though, you are going to have to communicate with django back at the server. Usually for javascript this client to server communication is done with Ajax.

    In essence, Ajax allows you to submit forms or reach URLs without reloading the page the user is on. You will need to create a URL and a view for it in the usual manner, then an ajax call to it in your JS code. That's a fair amount to set up.

    In fact, Ajax is a whole article subject in itself, but I have found this particular article very useful, especially as it does not rely on Jquery.