0
我是Django的新手,並且在this tutorial後面添加一個Like按鈕到模塊。我有這樣的看法:Django CSRF令牌丟失或FormView不正確
class VoteFormView(FormView):
form_class = VoteForm
def form_valid(self, form):
pic = get_object_or_404(UserPic, pk=form.data["pic"])
user = self.request.user
prev_votes = Vote.objects.filter(voter=user, pic=pic)
has_voted = (prev_votes.count() > 0)
if not has_voted:
# add vote
Vote.objects.create(voter=user, pic=pic)
print("voted")
else:
# delete vote
prev_votes[0].delete()
print("unvoted")
return render_to_response('userpics/photo.html',
{'pic':pic})
def form_invalid(self, form):
print("invalid")
return render_to_response('userpics/photo.html',
{'pic':pic})
在photo.html我:
{% if pic %}
<form method="post" action="/photo/vote/" class="vote_form">
<li> [{{ pic.votes }}]
{% csrf_token %}
<input type="hidden" id="id_pic" name="pic" class="hidden_id" value="{{ pic.pk }}" />
<input type="hidden" id="id_voter" name="voter" class="hidden_id" value="{{ user.pk }}" />
<button>Like</button>
</form>
<img class="pic" src="/static/assets/{{pic}}" />
{% endif %}
當我點擊第二次照片頁面上的鏈接一樣,我得到這個錯誤:
Forbidden (403)
CSRF verification failed. Request aborted.
我想:
return render_to_response('userpics/photo.html',
{'pic':pic,},
context_instance=RequestContext(request))
但由於此視圖沒有「請求」對象,因此上述語句也會導致錯誤。所以我不確定如何爲這個視圖實現csrf並感謝你的幫助。
感謝的人。這解決了這個問題。 – hbp