CSRF token missing or incorrect even though I have {% csrf_token %}

后端 未结 2 2243
不知归路
不知归路 2021-02-20 18:32

I have been getting this error referring to this method in my views.py file:

def AddNewUser(request):
    a=AMI()
    if(request.method == \"POST\"):
        pri         


        
2条回答
  •  一生所求
    2021-02-20 18:57

    You have to use a RequestContext object to get the context, then pass the results in to your render_to_response() function. RequestContext adds in a required CSRF token.

    from django.template import RequestContext
    from django.shortcuts import render_to_response
    
    csrfContext = RequestContext(request)
    return render_to_response(some_template, csrfContext)
    

    As a side note, you can also use RequestContext to add contexts/dictionaries intended for the template. For instance, I frequently use:

    initialData = {'form': theForm, 'user_status': 'online'}
    csrfContext = RequestContext(request, initialData)
    return render_to_response(show_template, csrfContext)
    

    As a (brief) explanation of what RequestContext does: most middleware creates something called a context processor, which is simply a function that supplies a context (dictionary) of variables. RequestContext looks for all the available context processors, gets their contexts, and appends them all to a single (giant) context.

提交回复
热议问题