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的内容,在输入框中输入数据,显示如下:
点击提交,显示如下:
POST方法提交表单数据处理
- 在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/”就好了。
- 在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)
- 在项目的urls.py文件,配置url,如:
urlpatterns = [ ... url(r'^search_post/', search.search_from_post), ...]
- 在浏览器中输入
127.0.0.1:8000/search_post/
,显示:
在输入框输入王者荣耀,点击搜索,显示
阅读全文
0 0
- Django 表单
- Django 表单
- Django表单
- Django-表单
- Django 表单
- django-表单
- Django 表单
- django表单
- Django表单
- Django-表单
- Django系列五:Django 表单
- django中搜索表单
- 自定义django表单
- Django中的表单类
- python django 表单
- Django表单处理
- Django Form表单
- Django 表单处理(二)
- Python学习零散杂记(2017-10-30)
- 1730-Northcott Game
- HCS12加载RAM并执行Bootloader用户指南
- 【六】机器学习之路——线性回归python实现(2)
- 安卓开发使用百度地图sdk实现定位,添加marker,城市切换等功能
- Django表单
- Oracle 11g安装与卸载
- sql sever客户端连接的问题
- 连接数据库错误
- Web前端开发最佳实践总结三:CSS最佳实践
- 椒盐噪声的图片 利用中值滤波效果好
- 单例模式的基本运用
- 设计模式之观察者模式
- NOI模拟(10.29)T3 颜色