Django: Make certain fields in a ModelForm required=False

后端 未结 5 1955
无人共我
无人共我 2021-02-02 06:08

How do I make certain fields in a ModelForm required=False?

If I have:

class ThatForm(ModelForm):
  class Meta:
    widgets = {\"text\": Textarea(require         


        
5条回答
  •  长情又很酷
    2021-02-02 06:45

    When we need to set required option on a bunch of fields we can:

    class ThatForm(forms.ModelForm):
    
        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
    
            for field in self.Meta.required:
                self.fields[field].required = True
    
        class Meta:
            model = User
            fields = (
                'email',
                'first_name',
                'last_name',
                'address',
                'postcode',
                'city',
                'state',
                'country',
                'company',
                'tax_id',
                'website',
                'service_notifications',
            )
            required = (
                'email',
                'first_name',
                'last_name',
                'address',
                'postcode',
                'city',
                'country',
            )
    

提交回复
热议问题