我想将jquery中声明的变量存储到django后端。
.js
<script>
var total=5;
</script>
我想将总计值(即 5)存储到 Total1 模型类中的得分字段。
我在 django 项目中有一个模型
模型.py
class total1(models.Model):
score = models.IntegerField(max_length = 50, blank = True,null = True)
我想将总计值存储在后端的得分字段中。
我需要在 View 和java脚本中写什么。
请帮助我。
最佳答案
您需要一个 <form>
要将值传递回您的 View ,在此形式中,您将需要一个与变量 total
关联的字段。 Django 提供了一些强大的帮助器来实现您的目标。
你真的需要看看 django 文档:https://docs.djangoproject.com/en/dev/topics/forms/
它的基本工作原理:
你有一个像你这样的模特:
模型.py:
class total1(models.Model): class total1(models.Model):
score = models.IntegerField(max_length = 50, blank = True,null = True)
您将需要一个 form.py 来保存由您的模型生成的表单,如下所示:
表单.py:
class YourTotalForm(ModelForm):
class Meta:
model = total1
widgets = {
'score': forms.HiddenInput(), #makes the textfield hidden, so you can deal with it via jQuery
}
现在您可以像这样获取表单的实例:
views.py:
def yourview(request):
# get a new instance of a total1 Form
form = YourTotalForm()
return render_to_response("mytemplate.html", {
"form": form,
现在,转到模板文件并输出表单对象。您将获得一个可见的文本字段,您可以使用它来操作分数字段。当然这不是你想要的,因为你使用jquery来操作这个值。 您需要修改文本字段小部件以使用隐藏字段。这就是我们在表单类中所做的
mytemplate.html:
<form action="" method="POST">
{{form}}
</form>
现在您应该只看到一个提交按钮。但是,如果您检查 html 输出,您会发现一个隐藏的表单字段,您可以使用 jquery 选择该字段以为其提供正确的值。当您点击提交时,您将需要 View 将值存储在数据库中。但只需查看我的答案开头提供的文档即可了解如何做到这一点。
关于jquery - 将jquery变量存储在django后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22913918/