Django--表单

GET 方法
1.我们在之前的项目中创建一个 search.py 文件,用于接收用户的请求:
/HelloWorld/HelloWorld/search.py 文件代码:
# -*- coding: utf-8 -*- 
from django.http import HttpResponse
from django.shortcuts import render_to_response 
# 表单
def search_form(request):
    return render_to_response('search_form.html') 
# 接收请求数据
def search(request):  
    request.encoding='utf-8'
    if 'q' in request.GET and request.GET['q']:
        message = '你搜索的内容为: ' + request.GET['q']
    else:
        message = '你提交了空表单'
    return HttpResponse(message)
 
2.urls.py 规则修改为如下形式:
/HelloWorld/HelloWorld/urls.py 文件代码:
from django.conf.urls import url
from . import view,testdb,search 
urlpatterns = [
    url(r'^hello$', view.hello),
    url(r'^testdb$', testdb.testdb),
    url(r'^search-form$', search.search_form),
    url(r'^search$', search.search),
]
 
POST 方法
1.在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)
2.urls.py 规则修改为如下形式:
/HelloWorld/HelloWorld/urls.py 文件代码:
from django.conf.urls import url
from . import view,testdb,search,search2
urlpatterns = [
    url(r'^hello$', view.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),
]
 
请求头中的: Content-Type: application/x-www-form-urlencoded request.POST中才会有值
解决:从 request.body里获取数据 然后再通过json.loads(request.body)
 
 

原文地址:https://www.cnblogs.com/absoluteli/p/13977605.html