使用Django框架表單
文章目錄
- 使用Django框架表單
- @[toc]
- 1.使用Form類構建表單
- 2.表單字段與Widget控件
文章目錄
- 使用Django框架表單
- @[toc]
- 1.使用Form類構建表單
- 2.表單字段與Widget控件
1.使用Form類構建表單
【創建項目和應用】
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】
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】
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']# 重定向到一個新的URLreturn 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】
<!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】
<!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】
from django.urls import path
from . import viewsurlpatterns = [path('', views.index, name='index'),path('userinfo/', views.userinfo, name='userinfo'),
]
文件路徑【FormSite/FormSite/urls.py】
from django.contrib import admin
from django.urls import include, pathurlpatterns = [path('formapp/', include('formapp.urls')),path('admin/', admin.site.urls),
]
文件路徑【FormSite/FormSite/settings.py】
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】
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】
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 dataif 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 requiredcontext = {}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 formelse:form = UserInfoForm()# render form in HTML templatereturn 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 dataif 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 requiredcontext = {}subject = form.cleaned_data['subject']message = form.cleaned_data['message']sender = form.cleaned_data['sender']cc_myself = form.cleaned_data['cc_myself']recipients = ['kingwjz@hotmail.com']if cc_myself:recipients.append(sender)# send_mail(subject, message, sender, recipients)context['subject'] = subjectcontext['message'] = messagecontext['sender'] = sendercontext['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 formelse:form = ContactForm()# render form in HTML templatereturn render(request, 'contact.html', {'form': form})
文件路徑【FormSite/formapp/templates/contact.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】
<!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】
from django.urls import path
from . import viewsurlpatterns = [path('', views.index, name='index'),path('userinfo/', views.userinfo, name='userinfo'),path('contact/', views.contact, name='contact'),
]
【訪問測試】