我是 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 %}
因此,我希望访问者选中他们同意的声明旁边的框,然后单击提交按钮。这样做会使语句的 votes 属性增加 1。我只是不知道如何获取用户输入并对数据库进行更改。
谢谢!