2017-10-10 151 views
0

表單字段不會顯示在瀏覽器中。只有提交按鈕出現。Django表單字段不會顯示在我的模板中

views.py代碼:

def vote(request, pk): 
    # check if request is post 
    if request.method == 'POST': 
     # create a form and populate it with data from request 
     form = forms.Vote(request.POST) 
     if form.is_valid(): 
      fact = Fact.objects.get(pk=pk) 
      fact.votes += int(form.cleaned_data['vote']) 
      fact.save() 
      return HttpResponseRedirect(reverse(
       'facts:detail', 
       args=(pk,) 
      )) 
    else: 
     form = forms.Vote() 
    return render(request, 'facts/fact_detail.html', {'form': form}) 

模板(fact_detail.html)代碼:

<form method='POST'> 
    {% csrf_token %} 
    {{ form }} 
    <input type="submit" value="vote" /> 
</form> 

Form類(forms.py)代碼:

VOTE_CHOICES = [ 
    (1, 'upvote'), 
    (0, 'downvote') 
] 


class Vote(forms.Form): 
    vote = forms.ChoiceField(choices=VOTE_CHOICES, widget=forms.RadioSelect()) 
+0

當您打印(形式)什麼是旅遊?你看到表單字段嗎? –

回答

0

views.py投票方法初始化形式變量本地,然後將它作爲參數傳遞。

def vote(request, pk): 
    form="" 
    //rest of the code// 
     return render(request, 'facts/fact_detail.html', {'form': form}) 
+0

沒有工作,並已經有一個初始化的本地表格 – hadyfarhat

+0

嘗試打電話form.is_valid.I打印form.errors後,我懷疑你沒有從request.post獲取數據或它可能是無效的。 –

+0

當我點擊提交(投票)按鈕,這將顯示在我的終端: '方法不允許(POST):/ facts/1/ [10/Oct/2017 13:35:03]「POST/facts/1/HTTP/1.1「405 0' – hadyfarhat