Rumah >pembangunan bahagian belakang >Tutorial Python >Python的Django框架中forms表单类的使用方法详解
Form表单的功能
Form相关的对象包括
Form Objects
Form对象封装了一系列Field和验证规则,Form类都必须直接或间接继承自django.forms.Form,定义Form有两种方式:
方法一:直接继承Form
from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100,label='主题') message = form.CharField(widget=forms.TextArea) sender = form.EmailField() cc_myself = forms.BooleanField(required=False)
方法二:结合Model,继承django.forms.ModelForm
#models.py class Contact(models.Model): title = models.CharField(max_length=30) content = models.CharField(max_length=20) #form.py class ConotactForm(ModelForm): class Meta: model = Contact field = ('title','content') #只显示model中指定的字段
在视图(view)中使用form
在view函数中使用form的一般情景是:
view.py:
form django.shortcuts import render form django.http import HttpResponseRedirect def contact(request): if request.method=="POST": form = ContactForm(request.POST) if form.is_valid(): #所有验证都通过 #do something处理业务 return HttpResponseRedirect('/') else: form = ContactForm() return render(request,'contact.html',{'form':form})
contact.html:
<form action='/contact/' method='POST'> {% for field in form %} <div class = 'fieldWrapper'> {{field.label_tag}}:{{field}} {{field.errors}} </div> {% endfor %} <div class='fieldWrapper'> <p><input type='submit' value='留言'></p></div> </form>
处理表单数据
form.is_valid()返回true后,表单数据都被存储在form.cleaned_data对象中(字典类型,意为经过清洗的数据),而且数据会被自动转换为Python对象,如:在form中定义了DateTimeField,那么该字段将被转换为datetime类型,还有诸如:IntegerField、FloatField
if form.is_valid(): subject = form.cleaned_data['subject'] message = form.cleaned_data['message'] sender = form.cleaned_data['sender'] cc_myself = form.cleaned_data['cc_myself'] recipients = ['info@example.com'] if cc_myself: recipients.append(sender) from django.core.mail import send_mail send_mail(subject, message, sender, recipients) return HttpResponseRedirect('/thanks/') # Redirect after POST
Form的简单使用方法就这些。 另:
在模版中显示表单的几种方式:
显示form找template中的方法多种多样,也可以自定义:
<form action="/contact/" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form>
还可以使用form.as_table、form.as_ul,分别表示用
标签,