First, the use of Modelform
Modelform has validation capabilities for user-submitted data, but it is much simpler than a form
fromdjango.forms importModelForm # 导入ModelFormclasscustomerModelForm(ModelForm): classMeta: model=models.UserInfo fields="__all__" labels={ ‘name‘:‘用户名‘, ‘password‘:‘密码‘, ‘qq‘:‘qq号‘, ‘‘:‘号‘, ‘roles‘:‘角色‘ }
Description
1.model: Corresponding table name
2.fields: Select the field list, ' __all__ ' is select all fields
3.exclude: Exclude Field List
4.widgets: Plugin List
5.labels: Front-end display field name
6.error_messages: Custom error prompt
7.localized_field: localization, such as: displaying data according to different time zones
In addition to these parameters, Modelform and form can define local hooks and global hooks.
2. Instantiate form object, pass in template, same form
model_form =Customermodelform ()returnrender(request,"index.html",{"model_form":model_form})
3, the front-end through the transmission of model_form display
<div class= "Row" >
{{model_form.errors}}
<form class= "Form-horizontal" method= "POST" >
{% Csrf_token%}
{% for field in model_form%}
<div class= "Form-group" >
<label class= "col-sm-2" style= "Font-weight:normal" >
{% if field.field.required%}
<b> {{Field.label}} (* required) </b>
{% Else%}
{{Field.label}}
{% ENDIF%}
</label>
<div class= "Col-sm-10" >
<span style= "color:red;" >{{field.errors}}</span>
{{field}}
</div>
</div>
{% endfor%}
</form>
</div>
4. After the form is submitted, the backend view verifies the submitted form by the following methods
model_form =customerModelForm(request.POST)ifmodel_form.is_valid(): model_form.save()
5. If you are modifying a record, you need to pass in the Record object
obj = customerModel.objects.get(id=obj_id) #查到原来的值model_form =customerModelForm(instance=user_obj) #传入值model_form =CustomerModelForm(request.POST, instance=obj) #将原来的值生成新值ifmodel_form.is_valid(): model_form.save()
Second, there are multiple model, do not want each model to write a modelform, the use of dynamic generation of Modelform class method
A, the function of the dynamically generated class:type (' ClassName ', (object,),dict (funname=fun))
Parameters:
1, the Name of class, string form;
2, inherit the collection of parents, note that Python supports multiple inheritance, if there is only one parent class, pay attention to the single element of tuple notation;
3, class method name and function binding, here we bind the function fun to the method name Funname, you can use:
SetAttr (classname, "Funname", fun) way to replace
Example:
def createmodelform (request,admin_obj):
Class Meta:
Model = Admin_obj.model
Fields = "__all__"
Def __new__ (CLS, *args, **kwargs):
For Field_name,field_obj in Cls.base_fields.items ():
Field_obj.widget.attrs[' class '] = ' Form-control '
If Field_name in Admin_obj.readonly_fields:
field_obj.widget.attrs[' disabled ') = True #在后台不能通过这种方式修改外键对应的字段, such as consultant
return forms. MODELFORM.__NEW__ (CLS)
def default_clean (self):
Print ("Cleaned data:", Self.cleaned_data)
dynamic_model_form = Type ("Dynamicmodelform", (Forms). Modelform,), {"Meta": meta})
setattr (Dynamic_model_form, "__new__", __new__)
setattr (dynamic_model_form, "clean", Default_clean)
return Dynamic_model_form
The above example can be dynamically generated according to the requirements of dynamic_model_form, need to use the time to call the Createmodelform function can be
Model_form = forms. Createmodelform (Request,admin_obj=admin_obj)
Python Unified dynamic creation of multiple model corresponding Modelform class (type () function)