For details about how to use forms in the Django framework of Python, djangoforms
Form Functions
- Automatically generate HTML form elements
- Check the validity of form data
- If a verification error occurs, re-display the form (data is not reset)
- Data type conversion (convert data of character type to corresponding Python type)
Form-related objects include
- Widget: a tool used to render HTML elements, such as the <Textarea> tag in HTML corresponding to forms. textarea
- Field: a Field in the Form object. For example, EmailField indicates the email Field. If this Field is not in a valid email format, an error occurs.
- Form: a collection of Field objects. It verifies and displays HTML elements.
- Form Media: CSS and JavaScript resources used to render forms.
Form Objects
The Form object encapsulates a series of fields and verification rules. The Form class must inherit from django. forms. Form directly or indirectly. There are two ways to define Form:
Method 1: directly inherit Form
From django import formsclass ContactForm (forms. form): subject = forms. charField (max_length = 100, label = 'topic ') message = form. charField (widget = forms. textArea) sender = form. emailField () cc_myself = forms. booleanField (required = False)
Method 2: Use Model to inherit django. forms. ModelForm
# Models. pyclass Contact (models. model): title = models. charField (max_length = 30) content = models. charField (max_length = 20) # form. pyclass ConotactForm (ModelForm): class Meta: model = Contact field = ('title', 'content') # show only the fields specified in the model
Use form in view
The general scenario of using form in the view function is:
View. py:
Form django. shortcuts import renderform django. http import HttpResponseRedirectdef contact (request): if request. method = "POST": form = ContactForm (request. POST) if form. is_valid (): # All verifications pass # do something to Process Business 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 = 'loop'> </p> </div> </form>
Process form data
Form. after is_valid () returns true, all form data is stored in form. in the cleaned_data object (the dictionary type indicates the cleaned data), and the data is automatically converted to a Python object. For example, DateTimeField is defined in form, this field will be converted to the datetime type, including: IntegerField and 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
This is the simple use of Form. In addition:
Several ways to display a form in a template:
You can use the following methods to find a template in the form:
<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 to display the form with <p> label, <table> label, and <ul> respectively. To customize the element, you only need to get the value of each element:
<form action="/contact/" method="post"> {{ form.non_field_errors }} <div class="fieldWrapper"> {{ form.subject.errors }} <label for="id_subject">Email subject:</label> {{ form.subject }} </div> <div class="fieldWrapper"> {{ form.message.errors }} <label for="id_message">Your message:</label> {{ form.message }} </div> <div class="fieldWrapper"> {{ form.sender.errors }} <label for="id_sender">Your email address:</label> {{ form.sender }} </div> <div class="fieldWrapper"> {{ form.cc_myself.errors }} <label for="id_cc_myself">CC yourself?</label> {{ form.cc_myself }} </div> <p><input type="submit" value="Send message" /></p></form>
You can use {form. name_of_field} to obtain each form field.
You can also use the iterative form. Each iteration element corresponds to the field in the form.
<form action="/contact/" method="post"> {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %} <p><input type="submit" value="Send message" /></p></form>
{Field} has the following attributes:
{Field. lable }}, for example, Email address {field. label_tag }}, for example, <label for = id_email> Email address </label> {field. value }}for example: someone.@gmail.com {field. errors }}
Example: Build a form
Step 1: first define a form model in models. py
Class RemarkForm (forms. form): subject = forms. charField (max_length = 100, label = 'message title') mail = forms. emailField (label = 'email ') topic = forms. choiceField (choices = TOPIC_CHOICES, label = 'select rating') message = forms. charField (label = 'message content', widget = forms. textarea) cc_myself = forms. booleanField (required = False, label = 'subscribe to this paid ')
Choices in that topic needs to define an array in models. py.
TOPIC_CHOICES = ('leve1', 'negative rating'), ('leve2', 'medium rating'), ('leve3', 'high rating '),)
In this way, the data of this model will be used in the html display form.
Another way to define a form model is to inherit another models directly. If we have designed a class (the table of the database) when designing a database in models and want to reuse the information of this class as a form model, it is very simple, it is also a class in models.
Class Advertisement (models. model): # Order Number OrderID = models. foreignKey (OrderInfo) # // ad Title # Title = models. charField (max_length = 36) # // ad Content # Content = models. charField (max_length = 600)
Note that its type is models. Model, which is used for database ORM.
How can we associate it?
You need to import a new class (ModelForm)
from django.forms import ModelFormclass ContactForm(ModelForm): class Meta: model = Advertisement fields = ('Title', 'CustomerID')
The Advertisement here is the old ORM model.
Step 2: OK. Continue with our form. What should we do next? Start calling the form in views. py.
Def remark (request ):
If request. method = 'post': # If the form is submitted form = ContactForm (request. POST) # obtain the Post form data if form. is_valid (): # verify the form return HttpResponseRedirect ('/') # Jump to else: form = ContactForm () # obtain the form object return render_to_response('message.html ', {'form': form ,})
The whole code is very simple, so I can't explain it much.
Step 3: We know that any access in django is managed through urls. py. Therefore, we need to configure a path.
(r'^message', 'iring.views.remark'),
Step 4: The final step is to create a template, because we finally output it to the html. Note that the last line of the remark function of views
return render_to_response('message.html', { 'form': form, })
When the preceding table is output to message.html, a form is automatically generated.
Therefore, first construct an html.
This html template is very simple. Aside from unnecessary CSS, I only want to provide the core part.
<Form action = "/message/" 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>
{% for field in form %}{% endfor %}
Used to traverse the elements in the form object, and then
{{ field.label_tag }}{{ field }} {{ field.errors }}
These three labels are output. Note that {field. errors} is not output by default. Content is output only when the form is verified.
Finally, we passed:
Http: // youdjangourl/message to access this example