2013-11-22 2 views
0

Django를 처음 사용하고 다음과 같이 this tutorial을 사용하면 모듈에 좋아요 버튼을 추가 할 수 있습니다. 나는이 같은 전망이 :FormView에 Django CSRF 토큰이 없거나 잘못되었습니다.

photo.html에서
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}) 

내가 가진 :

:

{% 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를 구현하는 방법을 모르며 도움을 주셔서 감사합니다.

답변

1

self.request를 사용하여 요청에 대한 액세스를, 그래서 시도 할 수

return render_to_response('userpics/photo.html', 
          {'pic':pic,}, 
          context_instance=RequestContext(self.request)) 
+0

감사 남자. 이것은 문제를 해결했습니다. – hbp