2013-03-11 142 views
2

型號:無法分配 「U'' 」: 「Vote.design」 必須是一個 「設計」 實例

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

我有這樣的錯誤:

ValueError at /vote/1/3/

Cannot assign "u'1'": "Vote.design" must be a "Design" instance.

回答

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('/') 
+0

1爲['get_object_or_404'](HTTPS://docs.djangoproject。 COM/EN /開發/主題/ HTTP /快捷鍵/#GET-對象或-404) – 2013-03-11 11:44:42

1

變化designdesign_id,它會改正錯誤

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

你需要找回Design模型的一個實例,並將Votedesign屬性指定爲:

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('/') 
相關問題