Django ModelForm与Form

管理员 pythonDjango ModelForm与Form已关闭评论17,5202字数 3909阅读13分1秒阅读模式

django表单系统中,所有的表单类都作为django.forms.Form的子类创建,包括ModelForm

关于django的表单系统,主要分两种文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

  • 基于django.forms.Form
  • 基于django.forms.ModelForm

表单API

表单有两种状态,绑定,未绑定 Form.is_bound()
Form.is_valid()
验证表单数据是否合法,返回True或者False文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

Form.errors 错误字典文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

Form.has_error(field,code=None)文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

Form.initial 在表单未绑定的情况下,为表单字段设置初始值,文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

>>> f=ContactForm(initial={'subject':'Hi there'})

Form.has_changed() 检查表单数据是否变化文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

From.cleaned_data 表单通过验证后,可以使用cleaned_data属性来访问‘清洁’的数据文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

Form.as_p() 将表单渲染成< p >标签
From.as_ul() 将表单渲染成< ul >标签
From.as_table() 将表单渲染成< table > 标签
但是这些都得自己添加<table ></table>;< ul >< /ul >标签文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

设置表单必填行与错误行的样式

Form.error_css_class
Form.required_css_class文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

from django import forms
class ContactForm(Form):
    error_css_class = 'error'      #错误行样式在HTML中表示class='error'
    required_css_class = 'required' #必填样式在Html中表示clss=‘required’

然后在css文件中定义error与required类就行了文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

配置表单元素的HTML id属性,< label >标签

Form.auto_id文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

>>> f = ContactForm(auto_id=False) #这样在html中表单不包含< label >标签
>>> f = ContactForm(auto_id=True) #在html中表单<label>标签将为每个表单的id
>>> f = ContactForm(auto_id='id_for_%s') #在html中表单<label>标签为id_for_字段id

From.prefix 可以为Django表单添加一个命名空间文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

>>> mother = PersonForm(prefix='mother')
>>> father = PersonForm(prefix='father')

Field.required 表示该字段为必填 缺省为必填项,如需要指定不为必须文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

>>> f=forms.CharField(required=True)

Field.label 表示友好的label,表单在页面显示时用到它文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

name=from.CharField(label="Your name")

Field.help_text 显示字段描述文本文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

Field.error_message 覆盖默认的错误信息文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

name = forms.CharField(error_messages={'required':'Please enter your name'}) #覆盖required的默认错误信息
widget

widget 负责渲染网页上的HTML表单文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

设置weidget实例样式 利用widget.attrs文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

class CommentForm(forms.Form):
    name=forms.CharField(widget=forms.TextInput(attrs={'class':'special'}))
    comment = forms.CharField(widget= forms.TextInput(attrs={'size':'40'}))

自定义了name字段的输入样式为类 special
comment更改的大小为40文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

内建的weidget

TextInput
NumberInput
EmailInput
URLInput
PasswprdInput
HiddenInput
DateInput 日期
DateTimeInput 日期/时间
TimeInput 时间
Textarea
CheckboxInput
Select
NullBooleanSelect 渲染成 unknown,yes,no三个选项
SelectMultiple
RadioSelect
CheckboxSelectMultiple 复选框列表
FileInput 文件上传
SelectDateWidget文章源自运维生存时间-https://www.ttlsa.com/python/django-modelform-and-form/

ModelForm表单

from django.forms import ModelForm
from myapp.models import Article
class ArticleForm(ModelForm):
    class Meta:
        model = Article  #表单对应的model
        fields = ['pub_date', 'headline', 'content', 'reporter']  #表单中显示的字段,对应models.py中对应的字段

使用的时候可以如下:

>>>form =  ArticleForm()
>>>article = Article.objects.get(pk=1)
>>>form = ArticleForm(instance = article)  #赋值instance可以使form表单是可以接受对象的数据

save()方法

每一个ModelForm都有一个save()方法,这个方法可以更具绑定的form表单创建并且保存一个数据库对象,ModelForm的子类可以接受一个model的子类作为instance的参数,如果存在那么save()方法会更新这个实例,否则会创建一个新的实例

save(commit=False)

save()方法接受一个commit的参数,其值为True或者False。默认为True。
如果你声明 save(commit=False),那么它就会返回一个还未保存至数据库的对象,这样的话 你可以用这个对象添加一些额外的数据,然后在用save()保存到数据库

def edit(request,sid):
    edit_obj = get_object_or_404(PointRule,id=sid)
    if request.method == 'POST':
        form = PointRuleForm(request.POST.copy(),instance=edit_obj)
        if form.is_valid():
            point = form.save(commit=False)
            point.update_user = request.user  #在form.save(commit=False时,添加一些表单中未有的数据)
            point.save()
            return redirect('point:index')
        else:
            messages.error(request, u'数据验证错误')
    else:
        form = PointRuleForm(instance=edit_obj)
        return render(request,'point/edit.html',locals())

save_m2m()方法

在save(commit=False)的时候,如果你的model中含有many-to-many的数据模型,那么你将无法使用save()方法去保存数据,只能使用save_m2m()方法来保存
在为声明ave(commit=False),则不用如此保存,用save()就好了..

Selecting the fields to use

1.选择model中所有字段为表单中的字段

__all__

例子

from django.forms import ModelForm
class AuthorForm(ModelForm)
    class Meta:
         model = Author
         fields='__all__'

2.剔除指定字段的所有数据 exclude

class PartialAuhorForm(ModelForm):
    class Meta:
        model = Author
        exclude = ['title'] #添加Author model中出了titile字段的所有字段至PartialAuhorForm表单

覆盖字段的默认值

form django.forms import ModelForm, Textarea
form myapp.models import Author
    class AuthorForm(ModelForm):
        class Meta:
            model=Author
            fields=('name','title','birth_date')
            widgets={'name':Textarea(attrs={'cols':80,'rows':20})}

 from django.utils.translation import ugettext_lazy as _
 class AuthorForm(ModelForm):
      class Meta:
          model=Author
          fields=('name','title','birth_date')
          labels = { 'name':_('Writer'), }
          help_texts = {'name':_('some useful help text.'),}
          error_messages={ 'name':{'max_length':_("this writer name is too long")} }
文/天天稀饭(简书作者)原文链接:http://www.jianshu.com/p/5664dd79c0ba
weinxin
我的微信
微信公众号
扫一扫关注运维生存时间公众号,获取最新技术文章~
管理员
  • 本文由 发表于 26/09/2016 11:51:12
  • 转载请务必保留本文链接:https://www.ttlsa.com/python/django-modelform-and-form/
  • django
  • django Form
  • django ModelForm
  • ModelForm