我希望将jquery中声明的变量存储到django后端。
.js
<script>
var total=5;
</script>我想在total1模型类中存储总计(即5)的值来得分字段。
我在django项目中有一个模型
model.py
class total1(models.Model):
score = models.IntegerField(max_length = 50, blank = True,null = True)我想在后端存储总分字段的值。
我需要在视图和java脚本中编写什么。
请帮帮我。
发布于 2014-05-08 03:24:01
我觉得这会帮到你.
您的html:
$('#myButton').click(function(){
var bjpFan=localStorage['bjpFan'];
var userid = //get the user id here to which you want to relate the score.
var total = parseInt(localStorage['total']);
$.ajax({
url: "/poll/score/",
type:"GET",
data: {total:total,userid:userid}
}).done(function(data){
alert(data);//do what you want to do with response
});
}); 你的urls.py:
url(r'/poll/score/$', 'score', name='score'),你的views.py
def score(request):
if request.is_ajax():
if request.method == 'GET':
user = UserProfile.objects.get(id=request.GET.get('userid'))
user.score = request.GET.get('total')
user.save()
return HttpResponse("%s" % user.score )希望这能帮到你
发布于 2014-04-07 14:27:33
您将需要一个<form>将值传递回您的视图,在这种形式中,您将需要一个与变量total相关联的字段。Django提供了一些强大的帮助来实现您的目标。
您确实需要查看django文档:https://docs.djangoproject.com/en/dev/topics/forms/
它基本上是如何工作的:
你有个像你这样的模特
models.py:
class total1(models.Model): class total1(models.Model):
score = models.IntegerField(max_length = 50, blank = True,null = True)您将需要一个包含由模型生成的表单的form.py,如下所示:
forms.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来操作这个值。您需要修改textfield小部件以使用隐藏字段。这就是我们在表单类中所做的
mytemplate.html:
<form action="" method="POST">
{{form}}
</form>现在,您应该只看到一个提交按钮。但是,如果检查html输出,就会发现一个隐藏的表单字段,您可以使用jquery进行选择,以给出正确的值。当您点击submit时,您将需要您的视图将该值存储在数据库中。但是,请看我在回答开始时提供的文档,了解如何做到这一点。
https://stackoverflow.com/questions/22913918
复制相似问题