2

楷模:

class Vote(models.Model):
    user = models.ForeignKey(User)
    design = models.ForeignKey(Design)
    vote = models.DecimalField(max_digits=2,decimal_places=1, choices=RATE_CHOICES)

意见:

def add_vote(request, id, vote):
    user = request.user
    Vote.objects.create(user=user, design = id, vote = vote)
    return HttpResponseRedirect('/')

网址:

url(r'^vote/(?P<id>\d+)/(?P<vote>\d{1,5})/', 'app.views.add_vote'),

例如,如果我尝试:

127.0.0.1:8000/投票/1/3

我有这个错误:

/vote/1/3/ 处的 ValueError

无法分配“u'1'”:“Vote.design”必须是“Design”实例。

4

3 回答 3

4

Vote.design必须是Design实例,而不是数字:

from django.http import Http404

def add_vote(request, id, vote):
    user = request.user
    try:
        design = Design.objects.get(pk=id)
    except Design.DoesNotExist:
        raise Http404

    Vote.objects.create(user=user, design=design, vote=vote)
    return HttpResponseRedirect('/')

或使用快捷方式:

from django.shortcuts import get_object_or_404

def add_vote(request, id, vote):
    user = request.user
    design = get_object_or_404(Design, pk=id)
    Vote.objects.create(user=user, design=design, vote=vote)
    return HttpResponseRedirect('/')
于 2013-03-11T11:43:11.323 回答
1

更改designdesign_id,它将修复您的错误

def add_vote(request, id, vote):
    user = request.user
    Vote.objects.create(user=user, design_id = id, vote = vote)
    return HttpResponseRedirect('/')
于 2013-03-11T11:42:46.447 回答
0

您需要检索Design模型的实例并将其design属性分配Vote给:

def add_vote(request, id, vote):
    user = request.user
    design = Design.objects.get(id=id)
    Vote.objects.create(user=user, design=design, vote=vote)
    return HttpResponseRedirect('/')
于 2013-03-11T11:42:53.630 回答