2009-07-15 78 views
64

我有一个表格,根据需要出现几个字段,当我不需要它们时。下面是从models.py形式Django以模型形式需要字段

class CircuitForm(ModelForm): 
    class Meta: 
     model = Circuit 
     exclude = ('lastPaged',) 
    def __init__(self, *args, **kwargs): 
     super(CircuitForm, self).__init__(*args, **kwargs) 
     self.fields['begin'].widget = widgets.AdminSplitDateTime() 
     self.fields['end'].widget = widgets.AdminSplitDateTime() 

在实际电路模型中,字段的定义是这样的:

begin = models.DateTimeField('Start Time', null=True, blank=True) 
end = models.DateTimeField('Stop Time', null=True, blank=True) 

我给这家views.py在这里:

def addCircuitForm(request): 
    if request.method == 'POST': 
     form = CircuitForm(request.POST) 
     if form.is_valid(): 
      form.save() 
      return HttpResponseRedirect('/sla/all') 
    form = CircuitForm()  
    return render_to_response('sla/add.html', {'form': form}) 

我能做些什么以便这两个字段不是必需的?

+1

没有办法,这些领域成为通过改变小部件所需。如果模型具有(null = True,blank = True),那么modelForm将它呈现为required = False。 – simplyharsh 2009-07-16 07:42:37

+0

看起来你是对的。字段本身不是必需的,但窗口小部件中的日期和时间字段是必需的。 – Ryan 2009-07-16 21:34:28

回答

102

如果你不想修改空白设置为你的域模型内部(这样做会破坏在管理网站正常验证),你可以做你的窗体类以下内容:

def __init__(self, *args, **kwargs): 
    super(CircuitForm, self).__init__(*args, **kwargs) 

    for key in self.fields: 
     self.fields[key].required = False 

重新定义构造函数不会损害任何功能。

+0

谢谢!它并不接受`blank = True`和我的自定义小部件。 – osa 2014-09-14 03:00:27

16

如果模型字段为空= True,则在表单字段中将required设置为False。否则,需要=真

是这么说的这里:http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

看起来你是对所做的一切。 您可以查看self.fields['end'].required的值。

+0

请注意,某些字段(例如`BooleanField`)在其构造函数(https://docs.djangoproject.com/en/dev/_modules/django/db/models/fields/#BooleanField)中具有空白=真硬编码。所以,设置blank = False会默默地失败。您必须在窗体的构造函数中使用`self.fields [...] .required = True`来强制这些字段所需的行为。另见https://code.djangoproject.com/ticket/22282。 – 2018-02-17 18:14:35

3

这不是一个答案,但对于通过Google发现此问题的其他人来说,还有一点数据:这发生在带有DateField的模型表单上。它需要设置为False,模型具有“null = True,blank = True”,并且如果在clean()方法期间查看它,则表单中的字段显示required = False,但它仍然说我需要一个有效的日期格式。即使当我明确地设置了input_formats = ['%Y-%m-%d','%m /%d /%Y','我没有使用任何特殊的小部件,并且我得到了“输入有效的日期” %m /%d /%y','']在表单字段上。

编辑:不知道它是否会帮助其他人,但我解决了我遇到的问题。我们的表单在字段中有一些默认文本(在这种情况下,单词“to”表示该字段是结束日期;该字段称为“end_time”)。我特意在表单的clean()方法中寻找单词“to”(我也尝试了clean_end_time()方法,但它从来没有调用过),并将012_中建议的clean_data变量的值设置为None。然而,这并不重要,因为(我猜)该模型的验证已经在无效日期格式“to”上呕吐,而没有给我一个截取它的机会。

+0

你解决了吗? – Don 2015-03-06 08:32:09

3

扩展在DataGreed的回答,我创建了一个mixin,允许你指定一个fields_required变量Meta类是这样的:

class MyForm(RequiredFieldsMixin, ModelForm): 

    class Meta: 
     model = MyModel 
     fields = ['field1', 'field2'] 
     fields_required = ['field1'] 

这里它是:

class RequiredFieldsMixin(): 

    def __init__(self, *args, **kwargs): 

     super().__init__(*args, **kwargs) 

     fields_required = getattr(self.Meta, 'fields_required', None) 

     if fields_required: 
      for key in self.fields: 
       if key not in fields_required: 
        self.fields[key].required = False 
0

model field documentation

如果你有一个模型,如下图所示,

class Article(models.Model): 
    headline = models.CharField(
     max_length=200, 
     null=True, 
     blank=True, 
     help_text='Use puns liberally', 
    ) 
    content = models.TextField() 

您可以在广告标题的表单验证改为required=True而不是blank=False作为模型如下所示定义字段。

class ArticleForm(ModelForm): 
    headline = MyFormField(
     max_length=200, 
     required=False, 
     help_text='Use puns liberally', 
    ) 

    class Meta: 
     model = Article 
     fields = ['headline', 'content'] 

所以回答这个问题,

class CircuitForm(ModelForm): 
    begin = forms.DateTimeField(required=False) 
    end = forms.DateTimeField(required=False) 
     class Meta: 
      model = Circuit 
      exclude = ('lastPaged',) 

这使得beginendrequired=False