django更换jinja2模板的csrf配置

1.settings.py中在 MIDDLEWARE中加上'django.middleware.csrf.CsrfViewMiddleware' 这个中间件

2.如果需要校验cookie中的csrf值,则在views.py中导入:

from django.core.context_processors import csrf

上下文参数改为形如:

class Login(View):
    def get(self, request):
        context = { 'args': args, 'condition': condition }
        # 生成一个csrf_token键值对加到到context中,后面form表单提交验证用
        context.update(csrf(request))
        return render(request, context, 'login.html')

同时模板HTML文件中的对应的Form表单中加一个验证token的input:

<input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">

如下形式:

<form action="." method="post">
    <!-- 这个input用作提交验证token -->
    <input type="hidden" name="csrfmiddlewaretoken" value="{{ csrf_token }}">
    
    <p>用户名:<input type="text" name="username"></p>
    <p>密码:<input type="password" name="password"></p>
    <p><input type="submit" value="登录"></p>
</form>

3.如果不需要校验cookie中的csrf值,则在views.py中导入

 from django.views.decorators.csrf import csrf_exempt

对应的视图函数加 @csrf_exempt 装饰器

原文地址:https://www.cnblogs.com/milesma/p/12464867.html