Form form functions
Form related objects include
Form Objects
The Form object encapsulates a series of Field and validation rules. The Form class must directly or indirectly inherit from django.forms.Form. There are two ways to define a Form:
Method 1: Directly inherit 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)
Method 2: Combine Model and inherit 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中指定的字段
Use form in view
The general scenario of using form in the view function is:
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>
Process form data
After form.is_valid() returns true, the form data is stored in the form.cleaned_data object (dictionary type, meaning cleaned data), and the data will be automatically converted into a Python object, such as: in form If DateTimeField is defined, then the field will be converted to datetime type, as well as: 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
These are the simple ways to use Form. Also:
Several ways to display forms in templates:
There are many ways to display form and template, and they can also be customized:
<form action="/contact/" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form>
You can also use form.as_table and form.as_ul, which respectively indicate using the
tag,