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

问题描述 投票:0回答:3
 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())

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

django django-forms
3个回答
81
投票

您可以修改表单中

__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/


13
投票

在 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']

0
投票
  1. 从 django 导入表单

  2. 类 ReminderForm(forms.ModelForm): 类元: 型号 = 电子邮件提醒 字段 = ['收件人电子邮件'] 小部件= { 'recipient_email': forms.EmailInput(attrs={ “必需”:正确 }),

     }
    
© www.soinside.com 2019 - 2024. All rights reserved.