The Django Model form component
This is a magical component, by name we can see that the function of this component is to combine the model and form, first a simple example to see how this thing is used: for example, our database has such a student table, the field has a name, age, Hobby, mailbox, telephone, address, Registration time and so on a lot of information, now let you write a page to create a student, your background should be how to write it? First we will be in front of a list of these fields, let the user to fill out, and then we from the day after tomorrow to receive a user input, create a new student object, save in fact, the focus is not these, but the legitimacy of validation, we need to determine the front-end user input is legitimate, such as the name must be within the number of characters Phone number must be a number of digits, the mailbox must be in the format of the mailbox these of course can be 1.1 points manual write limit, various judgments, this no problem, in addition to trouble we now have a more elegant (later in the Python-related content, to use the word "elegance", And get into the habit of the method: Modelform first to simple, blunt use it, and then to add verification conditions.
1. Create Modelform
#First Import Modelform fromDjango.formsImportModelform#In the view function, define a class, for example, called Studentlist, which inherits Modelform, writes a primitive class meta in this class (and notes that the first letter is capitalized)#In this primitive class, there are the following attributes (partial):classstudentlist (modelform):classMeta:model=student#The class in the corresponding modelFields ="__all__" #field, if it is __all__, means that all fields are listedExclude = None#excluded Fields #error_messages Usage:Error_messages = { 'name':{'Required':"user name cannot be empty",}, ' Age':{'Required':"age cannot be empty",}, } #widgets usage, such as the input box to enter the user name as textarea #first you have to import the module fromDjango.formsImportWidgets as Wid#because of the duplicate name, so the individual namesWidgets = { "name": Wid. Textarea (attrs={"class":"C1"})#You can also customize the properties } #labels, customizing the name displayed on the front endlabels= { "name":"User name" }
This class is then instantiated in a URL-corresponding view function, which is passed to the front-end
def student (Request): if Request.method = = ' GET ': student_list = studentlist () return render (Request, ' Student.html ', {' student_list ': student_list})
Then the front-end only need {{student_list.as_p}}, all the fields are out, you can display all with as_p, you can use the For loop this
Student_list, get a input box, now we don't have to as_p , manually put these input boxes out, as_p get the page is too ugly.
First for Loop this student_list, get student object, directly in front of print this student, is a input box Student.label, get the database of each field verbose_name, If you do not set this property, the default is the field name, but also through the student.errors.0 to get the error message with these, we can through the bootstrap to spell out the desired style, such as:
<body><div class= "Container" >
Now also missing a input box form-contral style, you can consider in the background widget inside the add
such as this:
From django.forms import widgets as Wid #因为重名, so the individual name widgets = {"Name": Wid. TextInput (attrs={' class ': ' Form-control '}), "Age": wid. Numberinput (attrs={' class ': ' Form-control '), "email": wid. EmailInput (attrs={' class ': ' Form-control ')}
Of course, can also be in JS, find all the input box, plus this style, also line.
2. Add a recordWhen you save the data, you don't have to fetch the data, just 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})
3. Edit DataIf you do not need to modelform, edit the time to display the previous data bar, you have to take the value, if modelform, only need to add a instance=obj (obj is to modify the database of a data object) can get the same effect
Keep in mind when saving, must pay attention to have this object (instance=obj), otherwise do not know which data to update
code example:
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 #对应的Model中的类 fields = "__all__" #字段, if it is __all__, it means to list all field exclude = None #排除的字段 labels = Non E #提示信息 help_texts = none #帮助提示信息 widgets = none #自定义插件 error_messages = None #自定义错误信息 #error_ Messages Usage: error_messages = {' name ': {' Required ': ' User name cannot be empty ',}, ' age ': {' required ': ' cannot be empty ',},} #widgets用法, such as the input box to enter the user name as textarea #首先得导入模块 from django.forms import widgets as Wid #因为重名, so an alias Widgets = {"Name": Wid. Textarea} #labels, customize the name displayed on the front labels= {"name": "Username"}def Student (Request): if Request.method = = ' GET ': student_list = Studentlist () return render (Request, ' student.html ', {' Studen T_list ': student_list}) Else:student_list = Studentlist (Request. POST) if Student_list.is_valid (): Student_list.save () return render (Request, ' student.html ', {' 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, ' Stu Dent_edit.html ', {' student_list ': student_list})
Summary: From the top you can see that modelform is very convenient to use, such as adding changes and other operations. But it also brings extra bad places, the model and the form are coupled. The Mf.save () method cannot commit the save directly if it is not coupled. But the use of coupled words is usually limited to small programs, writing large programs is best not.
python3-developing the Model form component in the Advanced Django-form assembly