gpt4 book ai didi

javascript - 为什么我不能在 Javascript 中使用 Django 的字符串变量?

转载 作者:行者123 更新时间:2023-11-28 14:46:20 25 4
gpt4 key购买 nike

我目前正在学习 Django/Python。我试图在 html 或 javascript 中使用 Django 变量,但它不能按我的意愿工作。我的 models.py 和views.py 文件看起来像

class Student(models.Model):
name = models.CharField(max_length=200)
password = models.CharField(max_length=200)

学生的名字是一个字符串变量,如“Tanaka”或“Yoshida”,密码是一个整数变量,1234或类似的东西。

View .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)

LogIn.html 文件中的脚本代码如下所示

<script>
{% for student in all_students %}
alert({{student.name}})
{% endfor %}
</script>

我想在这段代码中使用student.name,但这不起作用。如果我将student.name更改为student.password,它会按预期工作。问题是为什么student.password 出现在警报消息中,而student.name 却没有出现。我认为问题可能与名称和密码的变量类型有关。在这种情况下如何使用 Django 变量?提前谢谢您。

最佳答案

尝试:

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

在字符串中注入(inject)变量。

关于javascript - 为什么我不能在 Javascript 中使用 Django 的字符串变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46281318/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com