【问题标题】:csrf token missing in djangodjango 中缺少 csrf 令牌
【发布时间】:2016-02-17 02:27:53
【问题描述】:

我有一个关于 django csrf 的问题。这是我的视图代码。

    if request.user.is_authenticated():
      res = {"is_authenticated": "true"}
    else:
      res = {}

    return render_to_response('app/index.html', res, context_instance=RequestContext(request))

【问题讨论】:

标签: django csrf


【解决方案1】:

检查CsrfViewMiddleware 是否添加到settings.py 中的MIDDLEWARE_CLASSES 元组中,然后您只需在模板中执行{% csrf_token %} 即可获取令牌。

settings.py

MIDDLEWARE_CLASSES = (
    ...
    ...
    'django.middleware.csrf.CsrfViewMiddleware',
    ...
    ...
)

app/index.html

<form action="" method="post">{% csrf_token %}


更多信息请参考documentation

【讨论】:

    【解决方案2】:

    在你的views.py中,在你的函数上方使用@csrf_exempt装饰器,因为需要先像这样导入这个装饰器

    from django.views.decorators.csrf import csrf_exempt
    

    然后在你的视图函数中使用它。

    @csrf_exempt
    def sample_func(request):
        if request.user.is_authenticated():
            res = {"is_authenticated": "true"}
        else:
            res = {}
        return render_to_response('app/index.html', res, context_instance=RequestContext(request))
    

    然后在你的 index.html 文件中像这样在表单标签中调用这个装饰器

    <form method="" action="">
    {% csrf_token %}
    
    .......
    
    </form>
    

    【讨论】:

    • 没有。你不应该给出这样的建议。 CSRF 保护是有原因的;随机禁用它几乎总是错误的做法。
    猜你喜欢
    • 2019-07-28
    • 2017-07-27
    • 2019-06-01
    • 2017-12-19
    • 1970-01-01
    • 2020-02-10
    • 2017-01-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多