這個答案是不特定於Django的註冊,只是使用Django與Jinja2的一般。
如果Django的CsrfViewMiddleware確定您已經訪問了csrf_token上下文成員,則會設置csrf_token cookie。不幸的是,直到Django的中間件執行之後,才發生Jinja2渲染。因此,Cookie不會被設置,因此與表單不匹配,您將得到403錯誤。
要解決此問題,需要在完成處理響應之前的某個時間訪問上下文['csrf_token']。
如果您正在使用基於類的意見,你可以創建一個CsrfProtectMixin:
class CsrfProtectMixin(object):
def render_to_response(self, context, **response_kwargs):
# Csrf processing happens when using a RequestContext.
# Be sure to use one.
if not isinstance(context, RequestContext):
context = RequestContext(self.request, context)
# Force access to csrf_token due to the way jinja2 renders the template
# after middleware has finished processing. Otherwise, the csrf cookie
# will not be set.
str(context.get('csrf_token'))
return super(CsrfProtectMixin, self).render_to_response(context, **response_kwargs)
然後在您的視圖類:
class MyView(CsrfProtectMixin, TemplateView):
def get(self, request, *args, **kwargs):
context = {}
return self.render_to_response(context)
如果你不使用類爲主意見,你可以做這樣的事情:
def my_view(request):
context = RequestContext(request)
str(context['csrf_token']) #force access to the csrf_token
return render_to_response('template.html', context)
或者猴子補丁render_to_reponse與類中的邏輯,以上。
你的模板是什麼樣的? – JonC 2010-11-27 21:18:48
{%延伸 「site_base.html」 %} {%塊主體%} <形式方法= 「POST」 行動= 「/帳戶/登錄/」> \t {%csrf_token%} {{form.as_p} } {%endblock body%} – mgPePe 2010-11-27 22:21:23