方法一:自定义一个中间件
from django.utils.deprecation import MiddlewareMixin
from django.middleware.csrf import get_token
class CsrfTokenMiddleware(MiddlewareMixin):
def process_request(self, request):
get_token(request)
在配置文件settings.py 的中间件添加一行代码
'utils.csrfTokenMiddleware.CsrfTokenMiddleware'
方法二:在html文件下form表单中添加{% csrf_token %}
<div class="container">
<div class="row">
<h2 class="text-center">注册</h2>
<div class="col-md-8 col-md-offset-2">
<form action="" method="post">
{% csrf_token %}
<p>username:<input type="text" class="form-control" name="username"></p>
{# <p>username:<input type="text" class="form-control" name="username"></p>#}
<p>password:<input type="password" class="form-control" name="password"></p>
<input type="submit" class="btn btn-danger">
</form>
</div>
</div>
</div>
方法三:在view中使用method_decorator装饰器
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import ensure_csrf_cookie
class RegistView(View):
@method_decorator(ensure_csrf_cookie)
def get(self, request)
pass
def post(self, request)
pass