HTML Forms
<form action="/login" method="post">
<div>
<label for="username">Username: </label>
<input type="text" id="username" name="username" />
</div>
<div>
<label for="password">Password: </label>
<input type="password" id="password" name="password" />
</div>
<input type="submit" value="Login" />
</form>
GET & POST
- GET:当请求是要从服务器获取信息时,使用
GET
- POST:当请求是要修改服务器的数据时(上传文件、修改数据库数据),使用
POST
工作过程
-
GET
将提交的数据装换成字符串,以键值对的格式放入URL中(明文),然后发送到服务器 -
POST
将提交的数据进行编码,放入请求体中,然后发送到服务器
适用情形
GET:用于搜索内容(搜索的URL可以保存到书签中,便于分享)
POST:适用于上传大文件、二进制文件(图片)、提交敏感信息(密码)
Django Forms
Django FormsForms Class
# myapp/forms.py
from django import forms
class NameForm(forms.Form):
your_name = forms.CharField(label='Your name', max_length=100)
-
label
忽略时,Django 将根据 field name 自动生成,如your_name
--Your name
-
max_length
有两个作用:浏览器会限制输入;Django 会检验提交的值的长度
Views
Form# myapp/views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import NameForm
def get_name(request):
# if this is a POST request we need to process the form data
if request.method == 'POST':
# create a form instance and populate it with data from the request:
form = NameForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
# ...
# redirect to a new URL:
return HttpResponseRedirect('/thanks/')
# if a GET (or any other method) we'll create a blank form
else:
form = NameForm()
return render(request, 'name.html', {'form': form})
- 一般,渲染表单和处理表单都集成在同一个视图中,这样,可以重用一些逻辑
-
is.valid()
验证提交的数据- 验证成功:返回 True , 并将结果转换成对应的 Python 类型 并保存在
form.clean_data
中(字典) - 验证失败:返回 Flase
- 验证成功:返回 True , 并将结果转换成对应的 Python 类型 并保存在
- 成功处理表单后,要使用重定向;避免用户点击 “后退” 时,重复提交数据
模板
# myapp/templates/myapp/get_name.html
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit" />
</form>
- form 实例对象只会生成 Form Class 定义的 Widgets,自己还是要在模板中添加
<form>
标签 和{% cstf_token %}
在模板中使用 Django Forms
以下变量都需要自动添加 <form>
, {% csrf_token %}
, <input type="submit" />
{{ form }}
-
{{ form.as_table }}
: 将 label 和 widgets 放在<tr>
标签中,需要自己添加<table>
-
{{ form.as_p }}
:将 label 和 Widgets 放在<p>
中 -
{{ form.as_ul }}
:将 label 和 widgets 放在<li>
,需要自己添加<ul>
手动渲染 Django Forms
-
{{ form.non_field_errors }}
:class="errorlist nonfield"
-
{{ form.subject.errors }}
:class="errorlist"
-
{{ form.subject.label }}
:表示 label 的文字 {{ form.subject.id_for_label }}
{{ form.subject }}
-
{{ form.subject.label_tag }}
:{{ form.subject.id_for_label }}
+{{ form.subject }}
{% for field in form %}
<div class="fieldWrapper">
{{ field.errors }}
{{ field.label_tag }} {{ field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
{% endfor %}
网友评论