search
HomeBackend DevelopmentPython TutorialDetailed explanation of how to use the forms form class in Python's Django framework

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
  • 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

tag,

tag and
    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
Python: Automation, Scripting, and Task ManagementPython: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

Python and Time: Making the Most of Your Study TimePython and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Games, GUIs, and MorePython: Games, GUIs, and MoreApr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python vs. C  : Applications and Use Cases ComparedPython vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic ApproachThe 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Exploring Its Primary ApplicationsPython: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

How Much Python Can You Learn in 2 Hours?How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics in project and problem-driven methods within 10 hours?How to teach computer novice programming basics in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool