[Fixed]-Validation on CreateView and UpdateView in django always being triggered, even when model doesn't/shouldn't

1👍

It’s not because you added the widgets, it’s because you actually redefined the fields and while redefining them, you did not respect your model’s requirements. For example in your model

 mailing_address = models.ForeignKey(..., null=True, blank=True)

mailing address is allowed to be empty, but in your defined form field it’s required.

mailing_address = forms.ModelChoiceField(queryset=Address.objects.all(), widget=forms.Select(attrs={'tabindex':'7'}))
# You need required=False

If you want to redefine your own fields for the modelForm you can, then you need to respect your model while doing it. However, you can also accomplish what you’re trying by using already existing dictionaries in modelForm. For example inside your class Meta you can override the widgets like this:

 class YourForm(ModelForm):
     class Meta:
        model = YourModel
        fields = ('field_1', 'field_2', 'field_3', ...)
        widgets = {
            # CHANGE THE WIDGETS HERE IF YOU WANT TO
            'field_1': Textarea(attrs={'cols': 80, 'rows': 20}),
        }  
        labels ={
            # CHANGE THE LABELS HERE IF YOU WANT TO
        }

More info at Django’s modelForm docs: Overriding defaults field

Leave a comment