Python exploring ModelForm code details, pythonmodelform
This is a magic component. We can see through the name that the component function is to combine the model and form, right, you do not have to guess wrong, believe in your English level.
Let's take a simple example to see how to use this item:
For example, our database has such a student table with a large number of information such as name, age, hobbies, email, phone number, address, and registration time. Now let you write a page for creating students, what should you do on the background?
First, we will list these fields one by one at the front end, let the user fill in, then we will receive the user input one by one from the day after tomorrow, create a new student object, save
In fact, the focus is not on legality verification. We need to determine whether the user input is valid at the front end, such as the number of characters in the name and the number of digits in the phone number, the email address must be in the email format.
Of course, there can be 1.1 manual write restrictions and various judgments. This is no problem, except for the trouble.
We now have a more elegant method (in the future, we will use the word "Elegance" in Python-related content, and we will get used to it): ModelForm
It's easy to use first, use it bluntly, and then add the verification conditions:
First import ModelForm
from django.forms import ModelForm
In a view function, define a class, for example, StudentList. This class inherits ModelForm and then writes an original class Meta in this class (the writing method is required and the first letter is capitalized)
The original class has the following attributes (partial ):
Class StudentList (ModelForm): class Meta: model = models. student # fields = "_ all _" # field in the corresponding Model. If it is _ all __, indicates listing all the fields exclude = None # excluded fields labels = None # prompt information help_texts = None # help prompt information widgets = None # custom plug-in error_messages = None # custom errors information # error_messages usage: error_messages = {'name': {'required': "user name cannot be blank",}, 'age': {'required': "age cannot be blank ",},} # widgets usage. For example, you can set the input box of the input username to Textarea # first, you must import the module from django. forms import widgets as wid # Alias widgets = {"name": wid. textarea (attrs = {"class": "c1"}) # You can also customize attributes} # labels. The name displayed on the front end is labels = {"name ": "User Name "}
Then instantiate this class in the view function corresponding to the url and pass this object to the front-end.
def student(request): if request.method == 'GET': student_list = StudentList() return render(request,'student.html',{'student_list':student_list})
Then, you only need {student_list.as_p} at the front end, and all the fields will be displayed. You can use as_p to display all the fields, or use the student_list loop to obtain input boxes, now we don't need to use as_p. manually create these input boxes. The pages obtained by as_p are too ugly.
First for loop the student_list, get the student object, print the student directly on the front end, is an input box
Student. label. Get verbose_name of each field in the database. If this attribute is not set, the field name is obtained by default.
You can also get the error message through student. errors.0.
With this, we can use bootstrap to spell out the desired style.
For example:
<Body> <div class = "container">
A form-contral style in the input box is missing. You can add
For example:
From django. forms import widgets as wid # Alias widgets = {"name": wid. textInput (attrs = {'class': 'form-control'}), "age": wid. numberInput (attrs = {'class': 'form-control'}), "email": wid. emailInput (attrs = {'class': 'form-control '})}
Of course, you can also find all input boxes in js and add this style.
When saving the data, you don't need to take the data one by one. You just need to save it.
def student(request): if request.method == 'GET': student_list = StudentList() return render(request,'student.html',{'student_list':student_list}) else: student_list = StudentList(request.POST) if student_list.is_valid(): student_list.save() return redirect(request,'student_list.html',{'student_list':student_list})
Edit data:
If you do not need ModelForm, You have to display the previous data during editing. You have to obtain the value one by one. If ModelForm, you only need to add an instance = obj (obj is the object of a Data Record of the database to be modified) to achieve the same effect.
Note that this object (instance = obj) exists. Otherwise, you do not know which data to update.
Sample Code:
From django. shortcuts import render, HttpResponse, redirectfrom django. forms import ModelForm # Create your views here. from app01 import modelsdef test (request): # model_form = models. student model_form = models. student. objects. all () return render(request,'test.html ', {'model _ form': model_form}) class StudentList (ModelForm): class Meta: model = models. student # fields = "_ all _" # field in the corresponding Model. If it is _ all __, indicates listing all the fields exclude = None # excluded fields labels = None # prompt information help_texts = None # help prompt information widgets = None # custom plug-in error_messages = None # custom errors information # error_messages usage: error_messages = {'name': {'required': "user name cannot be blank",}, 'age': {'required': "age cannot be blank ",},} # widgets usage. For example, you can set the input box of the input username to Textarea # first, you must import the module from django. forms import widgets as wid # Alias widgets = {"name": wid. textarea} # labels: The name labels = {"name": "username"} def student (request): if request. method = 'get': student_list = StudentList () return render(request,'student.html ', {'student _ list': student_list}) else: student_list = StudentList (request. POST) if student_list.is_valid (): student_list.save () return comment ', {'student _ list': student_list}) def student_edit (request, pk): obj = models. student. objects. filter (pk = pk ). first () if not obj: return redirect ('test') if request. method = "GET": student_list = StudentList (instance = obj) return render(request,'student_edit.html ', {'student _ list': student_list}) else: student_list = StudentList (request. POST, instance = obj) if student_list.is_valid (): student_list.save () return render(request,'student_edit.html ', {'student _ list': student_list })
Summary
The above is all the details about the ModelForm code of Python exploration in this article. I hope it will be helpful to you. If you are interested, you can continue to refer to this site: Sample Code of the python programming goat door problem, and introduction of requests in python using the proxy proxies method. If you have any shortcomings, please leave a message. Thank you for your support!