Insert JavaScript variable into Django model

What I would like to do, is insert the value of a JavaScript variable into Django model. Any ideas, how could this be achieved?

I have a model with few fields, like:

class Cat(models.Model):
LOW = 0
HIGH = 2
(LOW, ‘Low’),
(NORMAL, ‘Medium’),
(HIGH, ‘High’),
(VERY_HIGH, ‘Very high’),
friendliness_level = models.IntegerField(choices=LEVEL_CHOICES, null=True)
attentiveness_level = models.IntegerField(choices=LEVEL_CHOICES, default=LOW)
sickness_level = models.IntegerField(choices=LEVEL_CHOICES, default=LOW)

Now, I’ve got a html form in which the user answers questions, each worth some amount of points. A script in JS sums those points in a variable. In the end, we have for example:

var friendliness = 30

What I would like to do now, is pass the value of this variable to django model as conditional statement:

if friendliness is lower than 5:
django Cat.friendliness_level = LOW
else if friendliness is lower than 20:
django Cat.friendliness_level = MEDIUM
django Cat.friendliness_level = HIGH

My question is, how do I pass the value from JS to Django model?

Always remember that the JavaScript is running in the browser, while Django is running on the server.

What you would need to do then is POST the data from the browser back to the server - generally either by submitting a form or submitting it as JSON through an AJAX call.

Yes, of course.
If I wanted to put simple input from HTML form, I’d use this instructions.

However, I’m not sure how to POST a JS variable that is calculated basing on user input from html form.

Your choice:

  • Use the variable to set the value of the form field before submitting the form.
  • Create a JSON object to be submitted through an AJAX call
  • Call a view passing that parameter as a URL parameter

Just remember though, you have no control over the data being submitted. The user always has the ability at any time to modify what gets submitted, so sanitize it carefully.