95

私はこのようなフォームを持っています:

class My_Form(ModelForm):
    class Meta:
        model = My_Class
        fields = ('first_name', 'last_name' , 'address')

住所フィールドをオプションとして設定するにはどうすればよいですか?

4

7 に答える 7

125
class My_Form(forms.ModelForm):
    class Meta:
        model = My_Class
        fields = ('first_name', 'last_name' , 'address')

    def __init__(self, *args, **kwargs):
        super(My_Form, self).__init__(*args, **kwargs)
        self.fields['address'].required = False
于 2015-05-22T18:54:43.580 に答える
114

あなたのモデルは次のようになっていると思います:

class My_Class(models.Model):

    address = models.CharField()

Django バージョン < 1.8 のフォーム:

class My_Form(ModelForm):

    address = forms.CharField(required=False)

    class Meta:
        model = My_Class
        fields = ('first_name', 'last_name' , 'address')

Django バージョン > 1.8 のフォーム:

class My_Form(ModelForm):

    address = forms.CharField(blank=True)

    class Meta:
        model = My_Class
        fields = ('first_name', 'last_name' , 'address')
于 2013-04-25T05:27:10.023 に答える
7

以下を追加する必要があります。

address = forms.CharField(required=False)
于 2014-08-07T16:42:26.830 に答える
6

Solution: use both blank=True, null=True.

my_field = models.PositiveIntegerField(blank=True, null=True)

Explanation:

If you use null=True

my_field = models.PositiveIntegerField(null=True)

then my_field is required, with * next to it in the form and you can't submit the empty value.

If you use blank=True

my_field = models.PositiveIntegerField(blank=True)

then my_field is not required, there won't be a * next to it in the form and you can't submit the value. But it will get null field not allowed.

Note: marking as not required and allowing null fields are two different things.

Pro Tip: Read the error more carefully than documentation.

于 2020-06-27T09:53:45.717 に答える
0

上記の答えは正しいです。null=Trueただし、ManyToManyField の設定はデータベース レベルでは効果がなく、移行時に次の警告が発生することに注意してください。

(fields.W340) null has no effect on ManyToManyField.

これに対する良い答えは、この別のスレッドで説明されています。

于 2019-09-05T10:15:08.647 に答える