2017-09-13 92 views
1

我是Django的新手,正在努力解決基本問題,但無法在線找到解決方案。Django視圖和foreignkey的基本邏輯

我有這些模型:

class Suggestion(models.Model): 
    author = models.ForeignKey('auth.User') 
    title = models.CharField(max_length=200) 
    description = models.TextField() 
    created_date = models.DateTimeField(default=timezone.now) 

    def __str__(self): 
     return self.title 


class Vote(models.Model): 
    suggestion = models.ForeignKey(Suggestion) 
    voter = models.ForeignKey('auth.User') 
    vote_count = models.IntegerField(default=1) 

我試圖創建一個將增加一個Vote給定Suggestion,捕捉誰投贊成票的用戶視圖。我已經看到有些人似乎用表單或常規函數來做這件事,所以不知道這裏最好的做法是什麼?

編輯

這是我嘗試(不工作)。任何幫助/建議表示讚賞。

#forms.py 
class VoteForm(forms.ModelForm): 

    class Meta: 
     model = Vote 
     fields =() 

#models.py 
class Vote(models.Model): 
    suggestion = models.ForeignKey(Suggestion) 
    voter = models.ForeignKey('auth.User') 
    vote_count = models.BooleanField() 

#views.py 
def add_vote(request, pk): 
    if request.method == 'POST': 
     form = VoteForm(request.POST) 
     suggestion = get_object_or_404(Suggestion, pk=pk) 
     if form.is_valid(): 
      vote = form.save(commit=False) 
      vote.voter = request.user 
      vote.vote_count = True 
      vote.save() 
      return render(request, 'suggestion/suggestion_detail.html', {'suggestion': suggestion}) 

#vote_form.html 
<form method="post"> 
    {% csrf_token %} 
    {{ form }} 
    <button type="submit">Vote</button> 
</form> 
+0

這是過於寬泛。您需要顯示您嘗試過的代碼,並提及您遇到的問題。 –

+0

什麼是'vote_count'字段。一個用戶可以多次投票同一個建議嗎? – schwobaseggl

+0

我已更新我的代碼,並提供更多詳細信息 – robtus88

回答

1

我已經成功地做什麼,我這樣想:

#vote_form.html 
    <form action="{% url 'add_vote' suggestion.id %}" method="post"> 
     {% csrf_token %} 
     <input type="submit" value="I want to vote"> 
    </form> 

    #urls.py 
    urlpatterns = [ 
     url(r'^suggestion/(?P<pk>\d+)/$', views.SuggestionDetail.as_view(), name="suggestion_detail"), 
     url(r'^suggestion/(?P<pk>\d+)/vote/$', views.add_vote, name='add_vote'), 
    ] 

    #models.py 
    class Vote(models.Model): 
     suggestion = models.ForeignKey(Suggestion) 
     voter = models.ForeignKey('auth.User') 
     vote_count = models.BooleanField() 

    #views.py 
    def add_vote(request, pk): 
     suggestion = get_object_or_404(Suggestion, pk=pk) 
     vote = Vote(
      suggestion = suggestion, 
      voter = request.user, 
      vote_count = True) 
     has_user_voted = Vote.objects.filter(voter=request.user, suggestion=suggestion).count() 
     if has_user_voted < 1: 
      vote.save() 
     else: 
      messages.error(request, 'It seems you have already voted, only one vote is allowed') 
     return HttpResponseRedirect(reverse('suggestion_detail', args=(suggestion.id,))) 
1

您應該爲投票創建一個表單並將其包含在Suggestion視圖中。表單可以有它自己的html - vote_form.html。然後用

{% include '[name of directory]/vote_form.html' %} 

至於計票包括它的建議html頁面上,除非你希望用戶投多票應該不是一個整數字段。如果您只希望某人能夠根據建議投票一次,則應該使vote_count成爲布爾字段(true或false)。然後,您可以將true賦予投票,將false賦予非投票。