Home >Backend Development >Python Tutorial >Detailed explanation of how to use the forms form class in Python's Django framework

Detailed explanation of how to use the forms form class in Python's Django framework

WBOY
WBOYOriginal
2016-07-21 14:53:171151browse

Form form functions

  • Automatically generate HTML form elements
  • Check the legality of form data
  • If validation error occurs, redisplay the form (data will not be reset)
  • Data type conversion (character type data is converted into the corresponding Python type)

Form related objects include

  • Widget: A tool used to render HTML elements, such as: forms.Textarea corresponds to the 4750256ae76b6b9d804861d8f69e79d3 tag in HTML
  • Field: A field in the Form object, such as: EmailField represents the email field. If this field is not a valid email format, an error will occur.
  • Form: a collection of Field objects, responsible for validating and displaying HTML elements
  • Form Media: CSS and JavaScript resources used to render forms.

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 e388a4556c0f65e1904146cc1a846bee tag, f5d188ed2c074f8b944552db028f98a1 tag and ff6d136ddc5fdfeffaf53ff6ee95f185 to indicate the display form. If you want to customize, you just 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&#63;</label>
  {{ form.cc_myself }}
 </div>
 <p><input type="submit" value="Send message" /></p>
</form>

Each form field can be obtained using {{form.name_of_field}}.

You can also iterate the 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}},如:Email address
{{field.label_tag}},如: <label for=id_email>Email address</label>
{{field.value}} 如:someone.@gmail.com
{{field.errors}}

Example: Building a form
Step one: First define a form model in models.py

class RemarkForm(forms.Form):
  subject = forms.CharField(max_length=100 ,label='留言标题')
  mail = forms.EmailField(label='电子邮件')
  topic = forms.ChoiceField(choices=TOPIC_CHOICES,label='选择评分') 
  message = forms.CharField(label='留言内容',widget=forms.Textarea)
  cc_myself = forms.BooleanField(required=False ,label='订阅该贴')

The choices in that topic need to define an array in models.py.

TOPIC_CHOICES = (
  ('leve1', '差评'),
  ('leve2', '中评'),
  ('leve3', '好评'),
)

In this way, the form displayed in HTML will use the data of this model.

There is another way to define a form model, which is to directly inherit another models. If when we design the database in models, we have already designed a class (that is, the table of the database) and then want to reuse the information of this class as the form model, then it is very simple, it is also a class in models

class Advertisement(models.Model): 
 #订单编号
 OrderID =  models.ForeignKey(OrderInfo)
 #//广告标题#
 Title = models.CharField(max_length = 36) 
 #//广告内容#
 Content = models.CharField(max_length = 600)

Note that its type is models.Model, which is used for database ORM.

Then how to connect?
Need to import a new class (ModelForm)

from django.forms import ModelForm

class ContactForm(ModelForm):
 class Meta:
 model = Advertisement
 fields = ('Title', 'CustomerID')

The Advertisement here is the model of the previous ORM.
Step 2: OK, let’s continue with our form. What should we do next? Start writing the calls to the form in views.py.
def remark(request):

  if request.method == 'POST': # 如果表单被提交
    form = ContactForm(request.POST) # 获取Post表单数据
    if form.is_valid(): # 验证表单
      return HttpResponseRedirect('/') # 跳转
  else:
    form = ContactForm() #获得表单对象
    
  return render_to_response('message.html', {
    'form': form,
  })


The whole code is very simple, so I won’t explain it too much.


Step 3: We know that any access in django is managed through urls.py. So below we need to configure a path.

 (r'^message', 'iring.views.remark'),

Step 4: Finally it is time to create a template, because we will eventually output it to html. Pay attention to the last line of the remark function of views

  return render_to_response('message.html', {
    'form': form,
  })

That is to say, the current form object is output to message.html and a form is automatically generated.
So, first build an html.
This html template is very simple. Without unnecessary CSS, I only give 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 %}

is used to traverse the elements in the form object, and then pass

{{ field.label_tag }}
{{ field }} 
{{ field.errors }}

To output these three tags, note that {{ field.errors }} will not be output by default. The content will only be output when the correctness of the form is verified.

Finally we passed:
http://youdjangourl/message to access this example

2016621145313568.jpg (463×521)

2016621145344436.jpg (433×383)

2016621145405787.jpg (434×350)

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn