我是Django的新手,但我正在建立一个人们可以就某些有争议的主题发表声明的网站。现在我只是为每次辩论手动添加了一些陈述,我希望用户能够在一份陈述中“投票”。
这是我现在的代码:
来自models.py的代码
class Debate(models.Model):
title = models.CharField(max_length=50)
description = models.CharField(max_length=100)
pub_date = models.DateTimeField('Date Published')
url_slug = models.SlugField(editable=False)
def __unicode__(self):
return self.title
class Statement(models.Model):
statement = models.CharField(max_length=200)
debate = models.ForeignKey(Debate)
votes = models.IntegerField(default=0)
user = models.ForeignKey(User)
def __unicode__(self):
return self.statement
来自views.py的代码
def debate_page(request, url_slug):
if request.method == 'POST':
for statement in statements:
statement.votes = statement.votes+1
debate = Debate.objects.get(url_slug=url_slug)
template = get_template('debate_page.html')
statements = Statement.objects.filter(debate=debate)
variables = Context ({
'debate_title': debate.title,
'debate_description': debate.description,
'statements': statements,
})
output = template.render(variables)
return HttpResponse(output)
模板代码
{% extends "base.html" %}
{% block title %}{{ debate_title }}{% endblock %}
{% block head %}{{ debate_title }}{% endblock %}
{% block description %}{{ debate_description }}{% endblock %}
{% block content %}
{% for statement in statements %}
<li>{{ statement }} - {{ statement.votes }}
<input type="checkbox" name="statement" value="{{ statement.id }}" /></li><br />
{% endfor %}
<input type="submit" value="Submit" />
{% endblock %}
所以我想要的是访问者查看他们同意的声明旁边的框,然后单击提交按钮。这样做会使语句的投票属性增加1.我无法弄清楚如何获取用户输入并对数据库进行更改。
谢谢!
答案 0 :(得分:43)
kyiphyu的代码可以使用F expressions进一步简化:
from django.db.models import F
Statement.objects.filter(id__in=statements).update(vote=F('vote') + 1)
答案 1 :(得分:0)
您可以使用
获取用户输入statements = request.POST.getlist('statement')
从该列表中,您可以增加投票计数并更新数据库,如
for st in statements:
statement = Statement.objects.get(id=st)
statement.vote += 1
statement.save()
希望这会对你有所帮助。