M
M
Maxim Dunayevsky2015-10-16 15:57:44
Django
Maxim Dunayevsky, 2015-10-16 15:57:44

How to set CSRF token in Django v1.8 in ClassBasedView?

Hello!
It used to work, but now this code has stopped:

from django.shortcuts import render_to_response
from django.template.context_processors import csrf
from django.views.generic import View


class Index(View):

    def get(self, request):
        context = {}
        context.update(csrf(request))
        return render_to_response('index.html', context)

The result of this code should be an HTML page containing sessionid and csrftoken among cookies , in fact I see only one cookie - sessionid . At the same time, all MIDDLEWARE and other settings are left by default. How to fix this problem (?) and force Django to set cookies for CSRF when rendering the template? This one doesn't work either:
def index(request):
    context = {}
    context.update(csrf(request))
    return render_to_response('index.html', context)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
Nerevar_soul, 2015-10-16
@dunmaksim

For FBV, you need to add {{ csrftoken }} in the template. CBV if the corresponding MIDDLEWARE is registered in case of FormView adds csrftoken automatically. In the case of a simple View, you can try to do it like in FBV. Or create a class based on FormView or FormMixin.

S
sim3x, 2015-10-16
@sim3x

stackoverflow.com/questions/29829021/django-csrf-v...

class LoginView(FormView):
  success_url = '/blog/edit/'
  form_class = AuthenticationForm
  template_name = 'blog/login.html'
  
  @method_decorator(sensitive_post_parameters('password'))
  @method_decorator(never_cache)<code></code>
  @method_decorator(requires_csrf_token)
  def dispatch(self, request, *args, **kwargs):
    return super(LoginView, self).dispatch(request, *args, **kwargs)

stackoverflow.com/questions/33052063/django-csrf-v...
class UserCreate(View):
  @method_decorator(csrf_exempt)
  def dispatch(self, request, *args, **kwargs):
    return super(UserCreate, self).dispatch(request, *args, **kwargs)

  def post():
  ....

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question