python - django request请求问题求助
大家讲道理
大家讲道理 2017-04-18 09:18:22
0
4
699

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),
]



views.py
# -*- 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'])



index.html
<!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网站 出现了



请问这是什么问题啊 要怎么解决啊 ?
大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

reply all(4)
巴扎黑

In Django, the following error is likely to occur when using post:

Forbidden(403):
CSRF verification failed. Request aborted.
Reason given for failure:
    CSRF token missing or incorrect.

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:

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

The problem will be solved


Questions I answered: Python-QA

小葫芦
在form中添加{{ csrf_token }}后再试试,form如下:
<form action="{% url 'home_page_show' %}" method="POST">
    {% csrf_token %}
    <input type="text" name="username">
    <button id="btn">提交</button>
</form>
Peter_Zhu

<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. .

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template