寒假自学1.16

POST 方法

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>title</title>
</head>
<body>
    <form action="/search-post/" method="post">
        {% csrf_token %}
        <input type="text" name="q">
        <input type="submit" value="搜索">
    </form>
 
    <p>{{ rlt }}</p>
</body>
</html>

提交数据时更常用POST方法。我们下面使用该方法,并用一个URL和处理函数,同时显示视图和处理请求。

我们在 templates 创建 post.html:

/HelloWorld/templates/post.html 文件代码:

在模板的末尾,我们增加一个 rlt 记号,为表格处理结果预留位置。

表格后面还有一个{% csrf_token %}的标签。csrf 全称是 Cross Site Request Forgery。这是Django提供的防止伪装提交请求的功能。POST 方法提交的表格,必须有此标签。

在HelloWorld目录下新建 search2.py 文件并使用 search_post 函数来处理 POST 请求:

/HelloWorld/HelloWorld/search2.py 文件代码:

# -*- coding: utf-8 -*- from django.shortcuts import render from django.views.decorators import csrf # 接收POST请求数据 def search_post(request): ctx ={} if request.POST: ctx['rlt'] = request.POST['q'] return render(request, "post.html", ctx)

urls.py 规则修改为如下形式:

/HelloWorld/HelloWorld/urls.py 文件代码:

from django.conf.urls import url from . import views,testdb,search,search2 urlpatterns = [ url(r'^hello/$', views.hello), url(r'^testdb/$', testdb.testdb), url(r'^search-form/$', search.search_form), url(r'^search/$', search.search), url(r'^search-post/$', search2.search_post), ]
原文地址:https://www.cnblogs.com/sunhongbin/p/14906107.html