Django 模型表单 - 设置必填字段 [英] Django Model Forms - Setting a required field

查看:64
本文介绍了Django 模型表单 - 设置必填字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 15 class Profile(models.Model):
 16     """
 17     User profile model
 18     """
 19     user = models.ForeignKey(User, unique=True)
 20     country = models.CharField('Country', blank=True, null=True, default='',
 21                                max_length=50, choices=country_list())
 22     is_active = models.BooleanField("Email Activated")

我有一个类似上面的模型,country 设置为 blank=True, null=True.

I have a model like above with country set to blank=True, null=True.

但是,在呈现给最终用户的表单中,我要求填写国家/地区字段.

However, in the form that is presented to the end user, I required the country field to be completed.

所以我像这样重新定义模型表单中的字段以强制"它成为必需的:

So I redefine the field in the Model Form like this to 'force' it to become required:

 77 class ProfileEditPersonalForm(forms.ModelForm):
 78 
 79     class Meta:
 80         model = Profile
 81         fields = ('email',
 82                   'sec_email',  
 83                   'image',
 84                   'first_name',
 85                   'middle_name',
 86                   'last_name',
 87                   'country',
 88                   'number',
 89                   'fax',)
 90 
 98     country =  forms.ChoiceField(label='Country', choices = country_list())

所以 country 字段只是一个例子(有很多).有没有更好的更干燥的方法来做到这一点?

So the country field is just an example (there are tons of them). Is there a better more DRY way of doing this?

推荐答案

您可以在表单中修改__init__中的字段.这是 DRY 的,因为标签、查询集和其他所有东西都将从模型中使用.这对于覆盖其他内容也很有用(例如,限制查询集/选择、添加帮助文本、更改标签等).

You can modify the fields in __init__ in the form. This is DRY since the label, queryset and everything else will be used from the model. This can also be useful for overriding other things (e.g. limiting querysets/choices, adding a help text, changing a label, ...).

class ProfileEditPersonalForm(forms.ModelForm):    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['country'].required = True

    class Meta:
        model = Profile
        fields = (...)

这是一篇描述相同技术"的博客文章:http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/

Here is a blog post that describes the same "technique": http://collingrady.wordpress.com/2008/07/24/useful-form-tricks-in-django/

这篇关于Django 模型表单 - 设置必填字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆