私はこのようなフォームを持っています:
class My_Form(ModelForm):
class Meta:
model = My_Class
fields = ('first_name', 'last_name' , 'address')
住所フィールドをオプションとして設定するにはどうすればよいですか?
私はこのようなフォームを持っています:
class My_Form(ModelForm):
class Meta:
model = My_Class
fields = ('first_name', 'last_name' , 'address')
住所フィールドをオプションとして設定するにはどうすればよいですか?
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
あなたのモデルは次のようになっていると思います:
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')
以下を追加する必要があります。
address = forms.CharField(required=False)
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.
上記の答えは正しいです。null=True
ただし、ManyToManyField の設定はデータベース レベルでは効果がなく、移行時に次の警告が発生することに注意してください。
(fields.W340) null has no effect on ManyToManyField.
これに対する良い答えは、この別のスレッドで説明されています。