Django : CSRF verification failed even after adding {% csrf_token %}

后端 未结 7 1266
轻奢々
轻奢々 2021-01-03 11:20

views.py:

def index(request):
    return render_to_response(\'index.html\', {})

def photos(request, artist):
    if not artist:
        r         


        
7条回答
  •  一整个雨季
    2021-01-03 11:48

    Supposing you are using a fairly recent version of Django (1.3/1.4/dev) you should follow these steps :

    • In settings.py, Add the middleware django.middleware.csrf.CsrfViewMiddleware to the MIDDLEWARE_CLASSES list.
    • In your template, use the {% crsf_token %} in the form.
    • In your view, ensure that the django.core.context_processors.csrf context processor is used either by :
      • use RequestContext from django.template
      • directly import the csrf processor from from django.core.context_processors

    Examples

    from django.template import RequestContext
    from django.shortcuts import render_to_response
    
    def my_view(request):
        return render_to_response('my_template.html', {}, context_instance=RequestContext(request))
    

    or

    from django.core.context_processors import csrf
    from django.shortcuts import render_to_response
    
    def my_view(request):
        c = {csrf(request)}
        return render_to_response('my_template.html', c)
    

    References

    • csrf in Django 1.3 or csrf in Django 1.4
    • RequestContext in Django 1.3 or RequestContext in Django 1.4

    (exhaustive post for posterity and future viewers)

提交回复
热议问题