Django(Form,ModelForm)
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Django(Form,ModelForm)相关的知识,希望对你有一定的参考价值。
FORM表单:
Django表单系统中,所有的表单类都作为django.forms.Form的子类创建,包括ModelForm
关于django的表单系统,主要分两种
基于django.forms.Form:所有表单类的父类
基于django.forms.ModelForm:可以和模型类绑定的Form
需求:向数据库的Info表中添加一些新的个人信息
FORM的用法
from django import forms from app01 import models from django.core.exceptions import ValidationError class Info_form(forms.Form): def validate_name(value): try: models.Info.objects.get(name=value) raise ValidationError(‘%s 的信息已经存在!‘%value) except models.Info.DoesNotExist: pass sex_choice=((0,‘男‘), (1,‘女‘))#select的数据可以像这样写,也可以在另外一张表中动态去拿 name = forms.CharField(validators=[validate_name],label=‘姓名‘,error_messages={‘required‘:‘必填‘}) age = forms.CharField(label=‘年龄‘,error_messages={‘required‘:‘必填‘}) # sex = forms.CharField(label=‘性别‘,error_messages={‘required‘:‘必填‘,},) sex=forms.IntegerField(widget=forms.widgets.Select(choices=sex_choice, attrs={‘class‘:‘setform2‘} )) birthday = forms.CharField(label=‘生日‘,error_messages={‘required‘:‘必填‘}) qualification = forms.CharField(label=‘学历‘,error_messages={‘required‘:‘必填‘}, widget=forms.TextInput(attrs={‘class‘:‘formset‘, ‘placeholder‘:‘本科‘ } )) email=forms.EmailField(max_length=100,min_length=10) job = forms.CharField(label=‘工作‘,error_messages={‘required‘:‘必填‘}) def __init__(self,*args,**kwargs): super(Info_form,self).__init__(*args,**kwargs) self.fields[‘hobby‘]=forms.CharField(widget=forms.widgets.Select(choices=models.Hobby.objects.values_list(‘id‘,‘item‘))) #-------------------------------------------------------views.py #------------------------------------------------------- from django.shortcuts import render,HttpResponse # Create your views here. from app01.models import * from app01.forms import * def add_info(req): if req.method==‘POST‘: Info_form_obj=Info_form(req.POST) if Info_form_obj.is_valid(): Info.objects.create(name=Info_form_obj.cleaned_data[‘name‘], age=Info_form_obj.cleaned_data[‘age‘], sex=Info_form_obj.cleaned_data[‘sex‘], birthday=Info_form_obj.cleaned_data[‘birthday‘], qualification=Info_form_obj.cleaned_data[‘qualification‘], job=Info_form_obj.cleaned_data[‘job‘] ) return HttpResponse(‘添加成功!‘) else: error_obj=Info_form_obj.errors print(‘***************‘) print(type(error_obj))#<class ‘django.forms.utils.ErrorDict‘> print(error_obj[‘name‘][0])#必填 print(error_obj.get(‘age‘))#<ul class="errorlist"><li>必填</li></ul> return render(req,‘add_info.html‘,{‘form_obj‘:Info_form_obj,‘error_obj‘:error_obj}) Info_form_obj=Info_form() return render(req,‘add_info.html‘,{‘form_obj‘:Info_form_obj}) #------------------------------------------------------add_info.html #------------------------------------------------------- <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>添加个人信息</title> <style> .formset{ color: rebeccapurple; border: dashed cadetblue; } </style> </head> <body> <form action="{% url ‘add_info‘ %}" method="post"> <p>姓名{{ form_obj.name }}{{ error_obj.name.0 }}</p> <p>年龄{{ form_obj.age }}{{ error_obj.age.0 }}</p> <p>生日{{ form_obj.birthday }}{{ error_obj.birthday.0 }}</p> <p>工作{{ form_obj.job }}<span>{{ error_obj.job }}</span></p> <p>学历{{ form_obj.qualification }}<span>{{ error_obj.qualification }}</span></p> <p>性别{{ form_obj.sex }}<span>{{ error_obj.sex }}</span></p> <p>邮箱{{ form_obj.email }}<span>{{ error_obj.email }}</span></p> <p>爱好{{ form_obj.hobby }}<span>{{ error_obj.hobby }}</span></p> {# {{ form_obj.as_p }}#} <input type="submit" value="提交"><br> {% csrf_token %} </form> </body> </html>
MODELFORM基本操作:
ModelForm
a.
class
Meta:
model,
# 对应Model的
fields
=
None
,
# 字段
exclude
=
None
,
# 排除字段
labels
=
None
,
# 提示信息
help_texts
=
None
,
# 帮助提示信息
widgets
=
None
,
# 自定义插件
error_messages
=
None
,
# 自定义错误信息(整体错误信息from django.core.exceptions import NON_FIELD_ERRORS)
field_classes
=
None
# 自定义字段类 (也可以自定义字段)
localized_fields
=
(
‘birth_date‘
,)
# 本地化,如:根据不同时区显示数据
如:
数据库中
2016
-
12
-
27
04
:
10
:
57
setting中的配置
TIME_ZONE
=
‘Asia/Shanghai‘
USE_TZ
=
True
则显示:
2016
-
12
-
27
12
:
10
:
57
b. 验证执行过程
is_valid
-
> full_clean
-
> 钩子
-
> 整体错误
c. 字典字段验证
def
clean_字段名(
self
):
# 可以抛出异常
# from django.core.exceptions import ValidationError
return
"新值"
d. 用于验证
model_form_obj
=
XXOOModelForm()
model_form_obj.is_valid()
model_form_obj.errors.as_json()
model_form_obj.clean()
model_form_obj.cleaned_data
e. 用于创建
model_form_obj
=
XXOOModelForm(request.POST)
#### 页面显示,并提交 #####
# 默认保存多对多
obj
=
form.save(commit
=
True
)
# 不做任何操作,内部定义 save_m2m(用于保存多对多)
obj
=
form.save(commit
=
False
)
obj.save()
# 保存单表信息
obj.save_m2m()
# 保存关联多对多信息
f. 用于更新和初始化
obj
=
model.tb.objects.get(
id
=
1
)
model_form_obj
=
XXOOModelForm(request.POST,instance
=
obj)
...
PS: 单纯初始化
model_form_obj
=
XXOOModelForm(initial
=
{...})
以上是关于Django(Form,ModelForm)的主要内容,如果未能解决你的问题,请参考以下文章