Django需要模型形式的字段

时间:2022-03-13 08:03:59

I have a form where a couple of fields are coming out as required when I don't want them too. Here is the form from models.py

我有一个表单,当我不需要的时候,几个字段会按要求出来。这是模型的形式。

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()

In the actual Circuit model, the fields are defined like this:

在实际的电路模型中,字段的定义如下:

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

My views.py for this is here:

我的观点。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})

What can I do so that the two fields aren't required?

我要怎么做才能不需要这两个字段呢?

6 个解决方案

#1


104  

If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class:

如果您不想修改模型中字段的空白设置(这样做会破坏管理站点中的常规验证),您可以在窗体类中执行以下操作:

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

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

The redefined constructor won't harm any functionality.

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

#2


17  

If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True

如果模型字段有blank=True,则required在表单字段上设置为False。否则,需要= True

Says so here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

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

Looks like you are doing everything right. You could check the value of self.fields['end'].required.

看起来你一切都做得很好。您可以检查self.fields['end'].required的值。

#3


3  

It's not an answer, but for anyone else who finds this via Google, one more bit of data: this is happening to me on a Model Form with a DateField. It has required set to False, the model has "null=True, blank=True" and the field in the form shows required=False if I look at it during the clean() method, but it's still saying I need a valid date format. I'm not using any special widget and I get the "Enter a valid date" message even when I explicitly set input_formats=['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', ''] on the form field.

这不是一个答案,但是对于任何通过谷歌找到这一点的人来说,还有一个数据:这是在一个带有DateField的模型表单上发生的。它要求设置为False,模型有“null=True, blank=True”,如果我在clean()方法中查看,表单中的字段显示required=False,但它仍然表示我需要一个有效的日期格式。我没有使用任何特殊的小部件,即使显式地在表单字段上设置input_formats=['%Y-%m-%d'、'%m/%d/%Y'、'%m/%d/%Y',我也会得到“输入一个有效日期”消息。

EDIT: Don't know if it'll help anyone else, but I solved the problem I was having. Our form has some default text in the field (in this case, the word "to" to indicate the field is the end date; the field is called "end_time"). I was specifically looking for the word "to" in the form's clean() method (I'd also tried the clean_end_time() method, but it never got called) and setting the value of the clean_data variable to None as suggested in this Django ticket. However, none of that mattered as (I guess) the model's validation had already puked on the invalid date format of "to" without giving me a chance to intercept it.

编辑:不知道它是否能帮助到其他人,但我解决了我遇到的问题。我们的表单在字段中有一些默认文本(在本例中,表示字段的单词“to”是结束日期;该字段称为“end_time”)。我特别在表单的clean()方法中寻找单词“to”(我还尝试了clean_end_time()方法,但它从未被调用),并将clean_data变量的值设置为None,如这个Django票据中建议的那样。然而,这些都不重要,因为(我猜)模型的验证已经在“to”的无效日期格式上出现了错误,而没有给我一个拦截它的机会。

#4


3  

Expanding on DataGreed's answer, I created a Mixin that allows you to specify a fields_required variable on the Meta class like this:

扩展DataGreed的答案,我创建了一个Mixin,允许您在Meta类上指定fields_required变量,如下所示:

class MyForm(RequiredFieldsMixin, ModelForm):

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

Here it is:

这里是:

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

#5


0  

This is a bug when using the widgets:

当使用小部件时,这是一个错误:

workaround: Using Django time/date widgets in custom form

解决方案:使用自定义形式的Django时间/日期小部件

or ticket 12303

或12303票

#6


0  

From the model field documentation,

从模型字段文档中,

If you have a model as shown below,

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

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

You can change the headline's form validation to required=True instead of blank=False as that of the model as defining the field as shown below.

您可以将标题的表单验证更改为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']

So answering the question,

回答这个问题,

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

this makes begin and end to required=False

这使得begin和end to required=False

#1


104  

If you don't want to modify blank setting for your fields inside models (doing so will break normal validation in admin site), you can do the following in your Form class:

如果您不想修改模型中字段的空白设置(这样做会破坏管理站点中的常规验证),您可以在窗体类中执行以下操作:

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

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

The redefined constructor won't harm any functionality.

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

#2


17  

If the model field has blank=True, then required is set to False on the form field. Otherwise, required=True

如果模型字段有blank=True,则required在表单字段上设置为False。否则,需要= True

Says so here: http://docs.djangoproject.com/en/dev/topics/forms/modelforms/

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

Looks like you are doing everything right. You could check the value of self.fields['end'].required.

看起来你一切都做得很好。您可以检查self.fields['end'].required的值。

#3


3  

It's not an answer, but for anyone else who finds this via Google, one more bit of data: this is happening to me on a Model Form with a DateField. It has required set to False, the model has "null=True, blank=True" and the field in the form shows required=False if I look at it during the clean() method, but it's still saying I need a valid date format. I'm not using any special widget and I get the "Enter a valid date" message even when I explicitly set input_formats=['%Y-%m-%d', '%m/%d/%Y', '%m/%d/%y', ''] on the form field.

这不是一个答案,但是对于任何通过谷歌找到这一点的人来说,还有一个数据:这是在一个带有DateField的模型表单上发生的。它要求设置为False,模型有“null=True, blank=True”,如果我在clean()方法中查看,表单中的字段显示required=False,但它仍然表示我需要一个有效的日期格式。我没有使用任何特殊的小部件,即使显式地在表单字段上设置input_formats=['%Y-%m-%d'、'%m/%d/%Y'、'%m/%d/%Y',我也会得到“输入一个有效日期”消息。

EDIT: Don't know if it'll help anyone else, but I solved the problem I was having. Our form has some default text in the field (in this case, the word "to" to indicate the field is the end date; the field is called "end_time"). I was specifically looking for the word "to" in the form's clean() method (I'd also tried the clean_end_time() method, but it never got called) and setting the value of the clean_data variable to None as suggested in this Django ticket. However, none of that mattered as (I guess) the model's validation had already puked on the invalid date format of "to" without giving me a chance to intercept it.

编辑:不知道它是否能帮助到其他人,但我解决了我遇到的问题。我们的表单在字段中有一些默认文本(在本例中,表示字段的单词“to”是结束日期;该字段称为“end_time”)。我特别在表单的clean()方法中寻找单词“to”(我还尝试了clean_end_time()方法,但它从未被调用),并将clean_data变量的值设置为None,如这个Django票据中建议的那样。然而,这些都不重要,因为(我猜)模型的验证已经在“to”的无效日期格式上出现了错误,而没有给我一个拦截它的机会。

#4


3  

Expanding on DataGreed's answer, I created a Mixin that allows you to specify a fields_required variable on the Meta class like this:

扩展DataGreed的答案,我创建了一个Mixin,允许您在Meta类上指定fields_required变量,如下所示:

class MyForm(RequiredFieldsMixin, ModelForm):

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

Here it is:

这里是:

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

#5


0  

This is a bug when using the widgets:

当使用小部件时,这是一个错误:

workaround: Using Django time/date widgets in custom form

解决方案:使用自定义形式的Django时间/日期小部件

or ticket 12303

或12303票

#6


0  

From the model field documentation,

从模型字段文档中,

If you have a model as shown below,

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

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

You can change the headline's form validation to required=True instead of blank=False as that of the model as defining the field as shown below.

您可以将标题的表单验证更改为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']

So answering the question,

回答这个问题,

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

this makes begin and end to required=False

这使得begin和end to required=False