Django从models创建表单(forms)

https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/

= ModelForm

对于映射到model的表单,避免重复定义属性,Django提供了一个帮助函数让你从一个Model直接创建Form.

from django.forms import ModelForm
from myapp.models import Article
#创建一个表单类
class ArticleForm(ModelForm):
    class Meta:
        model = Article
   fields = ['pub_date', 'headline', 'content', 'reporter']
# 创建一个表单用于添加文章
form = ArticleForm()
# 创建一个表单用于修改文章
article = Article.objects.get(pk=1)
form = ArticleForm(instance=article)

- 属性类型

映射关系:
Model field => Form field
AutoField Not represented in the form
BigIntegerField IntegerField with min_value set to -9223372036854775808 and max_value set to 9223372036854775807.
BooleanField BooleanField
CharField CharField with max_length set to the model field’s max_length
CommaSeparatedIntegerField CharField
DateField DateField
DateTimeField DateTimeField
DecimalField DecimalField
EmailField EmailField
FileField FileField
FilePathField FilePathField
FloatField FloatField
ForeignKey ModelChoiceField (see below)
ImageField ImageField
IntegerField IntegerField
IPAddressField IPAddressField
GenericIPAddressField GenericIPAddressField
ManyToManyField ModelMultipleChoiceField (see below)
NullBooleanField NullBooleanField
PositiveIntegerField IntegerField
PositiveSmallIntegerField IntegerField
SlugField SlugField
SmallIntegerField IntegerField
TextField CharField with widget=forms.Textarea
TimeField TimeField
URLField URLField

- 完整示例

from django.db import models
from django.forms import ModelForm
TITLE_CHOICES = (
    ('MR', 'Mr.'),
    ('MRS', 'Mrs.'),
    ('MS', 'Ms.'),
)
class Author(models.Model):
    name = models.CharField(max_length=100)
    title = models.CharField(max_length=3, choices=TITLE_CHOICES)
    birth_date = models.DateField(blank=True, null=True)
    def __str__(self):              # __unicode__ on Python 2
        return self.name

class Book(models.Model):
    name = models.CharField(max_length=100)
    authors = models.ManyToManyField(Author)

class AuthorForm(ModelForm):
    class Meta:
        model = Author
        fields = ['name', 'title', 'birth_date']

class BookForm(ModelForm):
    class Meta:
        model = Book
        fields = ['name', 'authors']

等价于下面的Form类定义 (除稍后讨论的save()方法):

from django import forms
class AuthorForm(forms.Form):
    name = forms.CharField(max_length=100)
    title = forms.CharField(max_length=3,
                widget=forms.Select(choices=TITLE_CHOICES))
    birth_date = forms.DateField(required=False)

class BookForm(forms.Form):
    name = forms.CharField(max_length=100)
    authors = forms.ModelMultipleChoiceField(queryset=Author.objects.all())

- 校验一个ModelForm

主要有两步:
1. 校验form
2. 校验model对象

Model Form校验被显示的触发,在调用is_valid(),或访问errors属性和调用full_clean()时.
Model校验在from校验阶段被触发,在form的clean()方法被调用后。

# 重写clean()方法
你可以重写clean()方法,以提供额外的校验。
绑定到一个model对象的model form包含一个instance属性,用于访问此特定对象。

# save()方法
>>> from myapp.models import Article
>>> from myapp.forms import ArticleForm
从POST数据创建一个实例
>>> f = ArticleForm(request.POST)
从form数据保存一个新文章对象
>>> new_article = f.save()
创建一个表单编辑已经存在的文章,但使用POST数据来填充form
>>> a = Article.objects.get(pk=1)
>>> f = ArticleForm(request.POST, instance=a)
>>> f.save()




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值