我是Django的新手,并且编程一般,每次有人点击模板中的按钮时,我都会尝试将IntegerField增加1。我已经研究了大约10个小时(我知道,很荒谬)没有运气......我认为这只是一件非常简单的事情,我刚才看了一下。我以为我用this或this问题解决了它,但我仍然无法得到它。
这是我的模板(我在单独的模板中用于{%include%}):
{% block body %}
<form method="post" action="/vote/">{% csrf_token %}
<input type="submit" name="endorsers" value="Endorse" />
</form>
{% endblock %}
Models.py:
class IdeaID(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length=30)
description = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', auto_now_add=True)
endorsers = models.IntegerField(default=0)
contributors = models.IntegerField(default=0)
backers = models.IntegerField(default=0)
def __unicode__(self):
return self.name
我的网址设置如下:
url(r'^vote/$', 'ideaMachine.views.vote'),
和Views.py:
@login_required
def vote(request):
if (request.method == 'POST') and ("endorsers" in request.POST):
idea_list = request.POST.getlist('ideaid')
for idea in idea_list:
ideaVote = IdeaID.objects.get(pk=idea)
ideaVote.endorsers += 1
ideaVote.save()
return render_to_response(
'vote_success.html', RequestContext(request)
)
从django的开发服务器,我得到一个“'POST / vote / HTTP / 1.1'200 58”。我不确定这是否有助于解决我的问题。帖子实际上并没有像我想要的那样更新我的代言人字段,但是 成功地将我发送到了vote_success.html。我在这一点上迷路了,任何帮助都会非常感激。提前谢谢!
答案 0 :(得分:0)
您可能正在尝试实施允许不同用户认可的功能。
以下是修改代码以使其工作的方法:
在vote.html模板中修改为:
<form method="post" action="/vote/">{% csrf_token %}
{% for ideaid in ideaids %}
<li>{{ ideaid.user }} - {{ ideaid.endorsers }}
<input type="checkbox" name="ideaid" value="{{ ideaid.id }}" /></li><br />
{% endfor %}
<input type="submit" name="endorsers" value="Endorse" />
</form>
我认为vote_success.html看起来像
{% for ideaid in ideaids %}
<li>{{ ideaid.user }} - {{ ideaid.endorsers }}
{% endfor %}
然后你可以修改views.py
views.py
from django.http import HttpResponse, HttpResponseRedirect
from django.template import Context, RequestContext, loader
from django.core.urlresolvers import reverse
from django.shortcuts import render, render_to_response
def vote(request):
if (request.method == 'POST') and ("endorsers" in request.POST):
idea_list = request.POST.getlist('ideaid')
for idea in idea_list:
ideaVote = IdeaID.objects.get(pk=idea)
ideaVote.endorsers += 1
ideaVote.save()
return HttpResponseRedirect(reverse('ideaMachine.views.vote_success', args=()))
ideaid = IdeaID.objects.all()
return render(request, 'vote.html', {'ideaids':ideaid})
def vote_success(request):
ideaid = IdeaID.objects.all()
return render(request, 'vote_success.html', {'ideaids':ideaid})
您还需要在网址中再输入一个条目:
url(r'^success/$', 'ideaMachine.views.vote_success'),