django csrf RequestContext

橙三吉。 提交于 2019-12-05 19:42:07

问题


If I include {% csrf_token%} in my form template and import RequestContext in my view,

do I have to include anything else in my view or will the csrf protection be taken care of just be the following:

from django.shortcuts import render_to_response
from django import forms
from django.http import HttpResponseRedirect
from django.template import Template, RequestContext
from dash.forms import GradeForm


def register(request):
    if request.method == 'POST':
        form = GradeForm(data=request.POST)
        if form.is_valid():
            new_dash_profile = form.save()
            new_user = form.save()
            return  HttpResponseRedirect("/success/")
        else:
            form = RegisterForm()
        return render_to_response('grade.html',{'form':form})

回答1:


To me, the easiest way is to add a RequestContext to the render_to_response function

return render_to_response('grade.html',
                          {'form':form},
                          context_instance=RequestContext(request))

This is just one possibility, the important thing is that you should process the csrf token somewhere, and RequestContext does that.

An other possibility is to do ir manually:

from django.core.context_processors import csrf

params = {}
params.update(csrf(request))
return render_to_response('grade.html', params)


来源:https://stackoverflow.com/questions/5691647/django-csrf-requestcontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!