I'm currently learning Django/Python. I'm trying to use Django variables in html or javascript, which doesn't work as I desire. My models.py, and views.py files look like
class Student(models.Model):
name = models.CharField(max_length=200)
password = models.CharField(max_length=200)
Students' name is a string variable, like "Tanaka" or "Yoshida", and password is an integer variable, 1234 or something like this.
views.py
def index(request):
all_students = Student.objects.all()
context = {'all_students': all_students}
template = loader.get_template('aaa/LogIn.html')
return render(request,'aaa/LogIn.html', context)
the script code in LogIn.html file looks like
<script>
{% for student in all_students %}
alert({{student.name}})
{% endfor %}
</script>
I want to use student.name in this code, but this doesn't work. If I change student.name to student.password, it works as expected. The question is why student.password appears in an alert message while student.name doesn't. I think the problem may be related to the variable type of name and password. How can I use Django variable in this case? Thank you, in advance.
alert("{{student.name}}")— you have to quote strings in JavaScript.