Form (2) and djangoform in Django

Source: Internet
Author: User

Form (2) and djangoform in Django

 

1. Save User input

If an error occurs after a user enters a form and submits it, the information is displayed again. We can save the user input information and return it to the front-end page, so that the user does not need to enter it again.

Views. py

1 # coding: UTF-8 2 from django. shortcuts import render, HttpResponse, redirect 3 from app01.forms import account as Account_Forms 4 5 6 def login (request): 7 8 obj = Account_Forms.UserInfo (request. POST) # Add the content entered by the user to the form object 9 if request. method = 'post': 10 return render (request, 'account/login.html ', {'obj': obj }) # return the content entered by the user to the front-end page 11 return render (request, 'account/login.html ', {'obj': obj })

 

Forms. py

1 from django import forms2 3 4 class UserInfo(forms.Form):5     username = forms.CharField()6     password = forms.CharField(widget=forms.PasswordInput())

 

Html file

 1 {% load staticfiles %} 2 <!DOCTYPE html> 3 

 

Ii. generate dynamic select statements

Select can be generated at the front end of form. select is generally divided into two types: 1. Data with unchanged content. 2. frequently changed data extracted from databases or files. For the implementation method of 1, see django form (1 ).

If the data is extracted from the database, adding, deleting, and modifying the content will happen frequently. If the implementation method of 1 is used, it is unrealistic, in this case, we need a method to implement dynamic select.

 Let's look at a piece of code first. It doesn't matter if you don't understand it:

Classes in form:

1 # coding: UTF-8 2 from django import forms 3 from app01 import models 4 5 6 class ImportForm (forms. form): 7 Host_List = (8 (1, 'Physical host'), 9 (2, 'vm ') 10) 11 host_type = forms. integerField (widget = forms. select (choices = Host_List) 12 hostname = forms. charField () 13 14 admin = forms. integerField (widget = forms. select () 15 16 def _ init _ (self, * args, ** kwargs): 17 super (ImportForm, self ). _ init _ (* args, ** kwargs) 18 19 self. fields ['admin']. widget. choices = models. simp. objects. all (). values_list ('id', 'username ')

 

 

The previous Code has actually implemented the dynamic select function in form. The following expanded select is the data extracted from the database:

 

We need to know the premise that djangoTo implement select in form, the passed parameter must be a data of the tuples type.

If you want to know why, how is it implemented, and why is it impossible to use the 1 implementation method, then patiently look down on the principle! This section does not belong to django knowledge point, but belongs to python object-oriented content.

We know that static fields can be defined in the python class. After static fields are loaded in the class, they are put into the memory. If you modify static fields again, the data in the memory will not change.. Why?

Because static fields belong to the class.
The static fields in the class will be loaded into the memory and belong to the content in the class. When the program is run for the first time,
It is loaded only once. Every time we create a class object, the _ init _ constructor under the class is executed by default.
Static fields belong to the class and do not belong to the object. Therefore, the content in the class will not be loaded again during each subsequent access.
Therefore, after we modify the data content in a file or database that is associated with a static field,
The data in the memory is not modified during the next access. (Unless we restart the Program)

 

How to do it?

Through the inheritance relationship of classes, we know that if the method to be executed is not in the current class, it will be automatically searched in the parent class, and if so, it will be executed.

We can use the defined form classRedefinition _ init __Method.

1     def __init__(self, *args, **kwargs):2         super(ImportForm, self).__init__(*args, **kwargs)3 4         self.fields['admin'].widget.choices = models.Simp.objects.all().values_list('id', 'username')

 

 

In the first sentence, run the _ init _ method in the parent class.

What does this line of code mean? You can search for the source code in the parent class.

Find the _ init _ method in the parent class. You can seeSelf. fields = copy. deepcopy (self. base_fields),

This statement sets all static fields in the form classDeep copyIn the object. In this way, we only need to modify the data in the object. The data under the class does not need to be changed.

Self. fieldsThe result isDictionaryYou can use ['admin'] To find the static fields defined in the form class:Admin= Forms. IntegerField (Widget= Forms. Select (Choices= Host_List ))

Pass. Widget. choicesYou can modify the parameters in the static field.

When the current page is accessed again, a new data is obtained, a new Meta Group is generated, and uploaded to the front-end html page. In this way, the dynamic select is implemented.

 

 

 

 

 

 

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.