0

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.

3
  • 5
    alert("{{student.name}}") — you have to quote strings in JavaScript. Commented Sep 18, 2017 at 14:07
  • I'd really suggest you don't store passwords in a charfield... if you're making a custom user model then you should follow the django docs.. Commented Sep 18, 2017 at 14:12
  • This web site is not something Im creating for job or anything serious. So, passwords are not actually a password. Still, thank you for your advice. Commented Sep 18, 2017 at 14:35

1 Answer 1

4

Try:

alert("{{student.name}}");

Inject variables in string.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.