1

我正在扩展基本的 django Poll 站点教程,并且我制作了一个视图,允许用户添加他们自己的投票。添加投票有效,添加选项无效。显然这是因为民意调查还不“存在”,并且 p.id 不能使用。但是,p.id 在底部重定向浏览器时起作用。有什么想法吗?

def save(request):
    p = Poll(question=request.POST['question'], pub_date=timezone.now())
    p.save()
    c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0)
    c2 = Choice(poll=p.id, choice_text=request.POST['c2'], votes=0)
    c3 = Choice(poll=p.id, choice_text=request.POST['c3'], votes=0)
    c4 = Choice(poll=p.id, choice_text=request.POST['c4'], votes=0)
    c1.save()
    c2.save()
    c3.save()
    c4.save()
    return HttpResponseRedirect(reverse('detail', args=(p.id,)))
4

1 回答 1

1

没关系,我想通了。选择不需要 id,而是需要对象。通过更改修复:

c1 = Choice(poll=p.id, choice_text=request.POST['c1'], votes=0)

c1 = Choice(poll=p, choice_text=request.POST['c1'], votes=0)
于 2013-07-06T17:15:24.993 回答