【问题标题】:What is the new version of csrf in Django 1.10Django 1.10 中的新版 csrf 是什么
【发布时间】:2017-05-26 17:05:49
【问题描述】:

我正在学习一个教程,并在这行代码中遇到了 TypeError:

c.update(csrf(request))

这是全图

from django.shortcuts import render
from django.views.decorators import csrf

def index(request):
    c = {} #dictionary called c
    c.update(csrf(request))
    return render(request, 'login/index.html', c)

我是在做一些改变的旧版本吗?我是否错误地导入了 csrf?我正在运行最新版本的 Django。

【问题讨论】:

  • 你得到的完整错误是什么?

标签: python django python-2.7 django-views csrf


【解决方案1】:

TypeError 是因为您导入了 csrf 装饰器而不是上下文处理器。应该是的。

from django.core.context_processors import csrf

但是,当您使用 render 快捷方式时,您不需要手动包含 csrf 令牌。它会使用包含 csrf 令牌的请求上下文自动呈现模板。

def index(request):
    c = {}  # dictionary called c
    return render(request, 'login/index.html', c)

render 快捷方式是在 Django 1.3 中引入的,因此多年来无需在视图中调用 csrf(request)(即使在 Django 1.3 之前,使用 render_to_responseRequestContext 可能更容易)。不幸的是,this example 一直保留在 Django 1.8 的文档中,因此它比应有的更常见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-14
    • 1970-01-01
    • 2017-07-03
    • 1970-01-01
    • 2016-12-06
    • 2017-10-09
    • 1970-01-01
    • 2012-02-24
    相关资源
    最近更新 更多