I am new to Django and following this tutorial to add a Like button to a module. I have views like this:
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})
In photo.html I have:
{% 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 %}
When I click the like link on a photo page for the second time, I get this error:
Forbidden (403)
CSRF verification failed. Request aborted.
I tried:
return render_to_response('userpics/photo.html',
{'pic':pic,},
context_instance=RequestContext(request))
But since this view does not have a 'request' object, the above statement causes an error too. So I'm not sure how to implement csrf for this view and appreciate your help.
Can access to the request using self.request
, so try:
return render_to_response('userpics/photo.html',
{'pic':pic,},
context_instance=RequestContext(self.request))