使用Django框架表单
### 文章目录
- [使用Django框架表单](#文章目录 使用Django框架表单 @[toc] 1.使用Form类构建表单 2.表单字段与Widget控件)
- [@[toc]](#文章目录 使用Django框架表单 @[toc] 1.使用Form类构建表单 2.表单字段与Widget控件)
- [1.使用Form类构建表单](#文章目录 使用Django框架表单 @[toc] 1.使用Form类构建表单 2.表单字段与Widget控件)
- [2.表单字段与Widget控件](#文章目录 使用Django框架表单 @[toc] 1.使用Form类构建表单 2.表单字段与Widget控件)
1.使用Form类构建表单
【创建项目和应用】
powershell
PS C:\Users\ls> cd E:\Python\
PS E:\Python> django-admin.exe startproject FormSite
PS E:\Python> cd .\FormSite\
PS E:\Python\FormSite> django-admin.exe startapp formapp
PS E:\Python\FormSite>
文件路径【FormSite/formapp/forms.py】
python
from django import forms
# Form Class : UserInfoForm
class UserInfoForm(forms.Form):
username = forms.CharField(label='Your name', max_length=32)
dep = forms.CharField(label='Your department', max_length=32)
email = forms.EmailField(label='Your email', max_length=64)
【代码分析】
通过CharField字段类型定义了一个表单字段username,对应于HTML表单form标签中的"用户名"文本输入框。
通过CharField字段类型定义了一个表单字段dep,对应于HTML表单form标签中的"部门"文本输入框。
通过EmailField字段类型定义了一个表单字段email,对应于HTML表单form标签中的"电子邮件"文本输入框。
文件路径【FormSite/formapp/views.py】
python
from django.shortcuts import render
# Create your views here.
def index(request):
return HttpResponse("This is formapp homepage.")
# class : UserInfoForm
from .forms import UserInfoForm
# 创建表单视图
def userinfo(request):
# 如果这是一个post请求,那么我们需要处理表单数据
if request.method == 'POST':
# 创建一个表单实例并用请求中的数据填充
form = UserInfoForm(request.POST)
# 检查表单是否有效
if form.is_valid():
# 按照要求处理表单中的数据
context = {}
context['uname'] = request.POST['username']
context['udep'] = form.cleaned_data['dep']
context['uemail'] = request.POST['email']
# 重定向到一个新的URL
return render(request, 'show_info.html', {'userinfo': context})
# return HttpResponseRedirect("#")
# 如果是GET(或其他任何方法),我们将创建一个空白表单
else:
form = UserInfoForm()
# 在HTML模板中渲染表单
return render(request, 'userinfo.html', {'form': form})
【代码分析】
通过if条件语句判断HTTP请求方法,如果为POST方法,则继续执行后面代码去接受用户提交的数据;如果为GET方法,则直接跳转到else,执行return,返回空的表单实例(form),让用户去录入数据再进行提交。
先通过request获取表单数据,再通过UserInfoForm表单类创建表单实例form。
通过if条件语句对表单实例form进行验证,如果所有的表单字段均有效,则继续执行下面的代码。
通过request获取表单字段数据,并保存在上下文变量context中。
将上下文变量context保存为字典类型变量userinfo,通过render()方法传递表单数据userinfo到新的页面中进行显示。
将表单实例form渲染到表单模板userinfo.html中。
文件路径【FormSite/formapp/templates/userinfo.html】
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/>
<title>Userinfo Form</title>
</head>
<body>
<h3>Userinfo Form</h3>
<form action="#" method="post">
{% csrf_token %}
{% for f in form %}
{{ f.label }}: {{ f }}<br><br>
{% endfor %}
<input type="submit" value="Submit" /><br>
</form>
</body>
</html>
【代码分析】
通过{% csrf_token %}模板标签为表单增加防护功能。django框架自带一个简单易用的"跨站请求伪造防护",当通过POST方法提交了一个启用CSRF防护的表单时,必须在表单中使用模板标签csrf_token。
通过{% for-endfor %}模板标签遍历表单实例form的每一项,并在页面模板中显示。
定义了表单提交按钮
文件路径【FormSite/formapp/templates/show_info.html】
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/>
<title>Show Userinfo</title>
</head>
<body>
<p>
userinfo (total):<br>
{{ userinfo }}<br>
</p>
<p>
userinfo (items):<br>
{% for key,value in userinfo.items %}
{{ key }} : {{ value }}<br>
{% endfor %}
</p>
</body>
</html>
【代码分析】
直接通过字典类型的上下文变量userinfo在页面模板中输出表单提交的数据信息。
通过{% for-endfor %}模板标签遍历字典类型的上下文变量userinfo中的每一项,并依次在页面模板中进行显示。
文件路径【FormSite/formapp/urls.py】
python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('userinfo/', views.userinfo, name='userinfo'),
]
文件路径【FormSite/FormSite/urls.py】
python
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('formapp/', include('formapp.urls')),
path('admin/', admin.site.urls),
]
文件路径【FormSite/FormSite/settings.py】
python
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'formapp.apps.FormappConfig',
]
【测试表单应用】
2.表单字段与Widget控件
文件路径【FormSite/formapp/forms.py】
python
from django import forms
# Form Class : UserInfoForm
class UserInfoForm(forms.Form):
username = forms.CharField(label='Your name', max_length=32)
dep = forms.CharField(label='Your department', max_length=32)
email = forms.EmailField(label='Your email', max_length=64)
# Form Class : ContactForm
class ContactForm(forms.Form):
subject = forms.CharField(label='Subject', max_length=64)
message = forms.CharField(label='Message', widget=forms.Textarea)
sender = forms.EmailField(label='Sender', max_length=64)
cc_myself = forms.BooleanField(required=False)
文件路径【FormSite/formapp/views.py】
python
from django.shortcuts import render
# Create your views here.
def index(request):
return HttpResponse("This is formapp homepage.")
# class : UserInfoForm
from .forms import UserInfoForm
# Create form view
def userinfo(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 = UserInfoForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
context = {}
context['uname'] = request.POST['username']
context['udep'] = form.cleaned_data['dep']
context['uemail'] = request.POST['email']
# redirect to a new URL:
return render(request, 'show_info.html', {'userinfo': context})
# return HttpResponseRedirect("#")
# if a GET (or any other method) we'll create a blank form
else:
form = UserInfoForm()
# render form in HTML template
return render(request, 'userinfo.html', {'form': form})
# class : ContactForm
from .forms import ContactForm
# Create form view
def contact(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 = ContactForm(request.POST)
# check whether it's valid:
if form.is_valid():
# process the data in form.cleaned_data as required
context = {}
subject = form.cleaned_data['subject']
message = form.cleaned_data['message']
sender = form.cleaned_data['sender']
cc_myself = form.cleaned_data['cc_myself']
recipients = ['[email protected]']
if cc_myself:
recipients.append(sender)
# send_mail(subject, message, sender, recipients)
context['subject'] = subject
context['message'] = message
context['sender'] = sender
context['cc_myself'] = cc_myself
# redirect to a new URL:
return render(request, 'show_contact.html', {'contact': context})
# return HttpResponseRedirect("#")
else:
print(form.errors)
print(form.errors.as_json())
# if a GET (or any other method) we'll create a blank form
else:
form = ContactForm()
# render form in HTML template
return render(request, 'contact.html', {'form': form})
文件路径【FormSite/formapp/templates/contact.html】
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/>
<title>Contact Form</title>
</head>
<body>
<h3>Contact Form</h3>
<form action="#" method="post">
{% csrf_token %}
{% for f in form %}
{{ f.label }}: {{ f }}<br><br>
{% endfor %}
<input type="submit" value="Submit" /><br>
</form>
</body>
</html>
文件路径【FormSite/formapp/templates/show_contact.html】
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="/static/css/mystyle.css"/>
<title>Show Userinfo</title>
</head>
<body>
<h3>Contact Info</h3>
<p>
contact (items):<br><br>
{% for key,value in contact.items %}
{{ key }} : {{ value }}<br><br>
{% endfor %}
</p>
</body>
</html>
文件路径【FormSite/formapp/urls.py】
python
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('userinfo/', views.userinfo, name='userinfo'),
path('contact/', views.contact, name='contact'),
]
【访问测试】