gpt4 book ai didi

django - Django模型表格-设置必填字段

转载 作者:行者123 更新时间:2023-12-03 13:40:44 25 4
gpt4 key购买 nike

 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

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

因此,我像这样重新定义了模型表单中的字段,以“强制”使其成为必需项:
 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())

因此,国家/地区字段只是一个例子(其中有很多)。有没有更好的DRY方法呢?

最佳答案

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

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/

关于django - Django模型表格-设置必填字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7682804/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com