urls.py
from django.conf.urls import url
from django.contrib import admin
from blog import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', views.index),
url(r'^abc$',views.handler),
]
# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def index(request):
return render(request,"index.html")
def handler(request):
return HttpResponse("<p>name:</p>" + request.POST['username'])
<!doctype html>
<html>
<head>
<meta charset="UTF-8"/>
<title>index page</title>
</head>
<body>
<form action="abc" method="POST">
<input type="text" name="username">
<button id="btn">提交</button>
</form>
</body>
</html>
我在谷歌浏览器下点击这个提交后出现了
我又直接打开abc网站 出现了
In Django, the following error is likely to occur when using post:
This is because Django helps us activate CSRF attack protection. CSRF (cross-site request forgery) is a malicious cross-site request or an attack that disguises the user. The attacker will trick the user's browser into accessing an authenticated website. website and perform some malicious operations. Since the user's browser has been authenticated by the website, the website will allow these operations to be performed with confidence (even if these operations are not required by the website or are not voluntary by the user).
So our server needs some protective measures. A common protection method is to use a random token generated by the server and include it in the form sent to the client. When the client sends back the form, the server checks whether the token was issued by itself, thus preventing attacks.
Since it is in
settings.py
檔中的MIDDLEWARE_CLASSES
中有預設的'django.middleware.csrf.CsrfViewMiddleware'
, Django will require CSRF token verification here. In order to make our website more secure, we should follow the rules of the game step by step!The
<form>
中加入{% csrf_token %}
in html is as follows:The problem will be solved
Questions I answered: Python-QA
<button id="btn">Submit</button> is written as <input type="submit" value="submit">, of course {% csrf_token %} cannot be missing
There is a simpler way to comment out the csrf configuration in the settings file. .