Django模型表单 - 设置必填字段

sup*_*er9 17 django django-forms

 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")
Run Code Online (Sandbox Code Playgroud)

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

但是,在提交给最终用户的表格中,我要求完成国家/地区字段.

因此,我在模型表单中重新定义了这样的字段,以"强制"它成为必需:

 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())
Run Code Online (Sandbox Code Playgroud)

所以国家领域只是一个例子(有很多).有更好的干燥方式吗?

and*_*lme 53

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

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

    class Meta:
        model = Profile
        fields = (...)
Run Code Online (Sandbox Code Playgroud)

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

  • 在这种情况下,需要调用super __init __(即ModelForm .__ init__)来为此表单实例设置self.fields.它还进行了一系列使用表单对象所必需的初始化.这是一个标准的OO练习,除非您完全替换方法,否则您可能需要以某种方式调用超类方法. (5认同)

cik*_*omo 9

例如,在 Django 3.0 中,如果您想在用户注册表中设置电子邮件,您可以设置required=True

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm


class MyForm(UserCreationForm):
    email = forms.EmailField(required=True) # <- set here

    class Meta:
        model = User
        fields = ['username', 'email', 'password1', 'password2']
Run Code Online (Sandbox Code Playgroud)

  • 感谢您添加这个,这比重写 `__init__()` 更干净、更简单。 (2认同)