django replace jinja2 template configuration csrf

1.settings.py in plus MIDDLEWARE in 'django.middleware.csrf.CsrfViewMiddleware'this middleware

2. If the checksum csrf cookie value, then introduced in the views.py:

from django.core.context_processors import csrf

Context parameters to the form:

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')

Meanwhile Form Form corresponding HTML template files added an authentication token of input:

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

The following form:

<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. If csrf value need not check the cookie, then introduced in the views.py

 from django.views.decorators.csrf import csrf_exempt

Corresponding to the view function plus @csrf_exempt decorator

Guess you like

Origin www.cnblogs.com/milesma/p/12464867.html