2017-02-23 23 views
0

The Error Message 的get()不帶任何關鍵字參數:Django的教程不同型號

這裏是views.py

def gambling(request, profile_id): 
     Profile = get_object_or_404(profile, pk=profile_id) 
     coin = get_object_or_404(Coin, pk=profile_id) 
     try: 
      selected_choice = coin.Face.get(pk=request.POST['name']) 
     except (KeyError, Coin.DoesNotExist): 
      # Redisplay the question voting form. 
       return render(request, 'gamble/detail.html', { 
       'Profile': Profile, 
       'error_message': "You didn't select a choice.", 
      }) 
     else: 
      selected_choice.Face 
      selected_choice.save() 
     return HttpResponseRedirect(reverse('gamble:results', args=(profile.id,))) 

這裏我賭博的看法是在detail.html

{% if error_message %}<p><strong>{{ error_message }}</strong></p>{% endif %} 
<form action="{% url 'gamble:gambling' Profile.id %}" method="post"> 
{% csrf_token %} 
{% for choice in coin.Face %} 
    <input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /> 
    <label for="choice{{ forloop.counter }}"> {{ choice }}</label><br /> 
{% endfor %} 

<input type="submit" value="flip" /> 
</form> 
形式

這裏是我的代碼模型配置文件和硬幣models.py

# Create your models here. 
class profile(models.Model): 
    name = models.CharField(max_length=120) 
    description = models.TextField(default='description default text') 
    def __unicode__(self): 
     return self.name 


class Coin(models.Model): 
    #choice = models.ForeignKey(BetAmount, on_delete=models.CASCADE) 
    choice_text = models.CharField(max_length=200, default="...") 
    flip = randint(0,1) 
    Heads =0 
    Tails =1 
    Face ={ 
    "Heads": Heads, 
    "Tails": Tails 
    } 

    def __str__(self): 
     return self.choice_text 
    def flipped(self): 
     return self.flip 

儘管我傳遞了表單名稱,但我不確定它是否與Coin對象本身有關,但我很清楚在這個問題上會有所幫助。 在Coin模型中是否存在某些問題,或者問題仍然存在於detail.html中,我似乎已儘可能接近教程示例編寫代碼。

+2

逐字地發佈完整的錯誤消息。不要複述。 –

+0

回溯將*告訴你它是否與Coin對象有關。發表它。 –

回答

2

coin.Facedict,而不是一個QuerySet

Face = { 
    "Heads": Heads, 
    "Tails": Tails 
} 

dict一個的get方法 - get(key[, default]) - 確實沒有采取任何關鍵字參數,但只有一個key,和 - 可選的 - 默認的回報價值,都是位置論據。

coin.Face.get('Head', coin.Heads) # for instance 
+0

謝謝澄清。 我應該怎麼做才能從POST表單獲取Face? – timi95

+0

假設face在POST ['Face']'中是一個字符串('Heads'或'Tails'),你可以這樣做:'selected_choice = coin.Face.get(request.POST ['Face'], coin.Heads)'在哪裏 – schwobaseggl

+0

這似乎進入異常,並給我我的error_message。 – timi95

相關問題