Django表单

来源:互联网 发布:阿里云开启3306端口 编辑:程序博客网 时间:2024/05/23 11:54

Django表单

GET方法请求处理

在testdjango项目中,创建一个search.py文件,文件内容:

from django.http import HttpResponsefrom django.shortcuts import render_to_response# 表单def search_from(requset):    return render_to_response('search_from.html')def search(request):    request.encoding = 'utf-8'    if 'q' in request.GET:        message = '你搜索的内容为:' + request.GET['q']    else:        message = '你提交了空表单'    return HttpResponse(message)

在templates目录下创建一个search_from.html的文件,文件内容:

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <title>Title</title></head><body><form action="/search" method="get">    <input type="text" name="q"/>    <input type="submit" value="搜索"/></form></body></html>

在testmodel/urls.py文件下,配置url的路径:

urlpatterns = [    ...    url(r'^search_from/', search.search_from),    url(r'^search/', search.search),    ...]

在浏览器中输入127.0.0.1:8000/search_from,显示search_from.html的内容,在输入框中输入数据,显示如下:

image

点击提交,显示如下:

image


POST方法提交表单数据处理

  1. 在templates目录下创建一个search_from_post.html的文件,文件内容为:
<!DOCTYPE html><html lang="en"><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>{{ content }}</p></body></html>

备注:form表单的action,如果写成”/search_post”,会报错,如:

RuntimeError at /search_postYou called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/search_post/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

写成”/search_post/”就好了。

  1. 在search.py文件创建一个方法search_from_post,如:
from django.shortcuts import renderdef search_from_post(request):    context = {}    context['content'] = ''    if request.POST:        context['content'] = request.POST['q']        print(context)    return render(request=request, template_name='search_from_post.html', context=context)
  1. 在项目的urls.py文件,配置url,如:
urlpatterns = [    ...    url(r'^search_post/', search.search_from_post),    ...]
  1. 在浏览器中输入127.0.0.1:8000/search_post/,显示:

image

在输入框输入王者荣耀,点击搜索,显示

image

image

原创粉丝点击