Override data validation on one django form element

后端 未结 2 1846
暗喜
暗喜 2020-12-30 06:18

I have a select list dropdown box on my form that is populated with data from a Model (Directors). The value of this dropdown doesn\'t need to be saved; it is really only u

相关标签:
2条回答
  • 2020-12-30 06:40

    For some reason the accepted answer didn't work for me (don't know if it's cause things have changed, or I'm using an inline form or what), but overriding full_clean worked:

    class MyForm(forms.ModelForm):
        def full_clean(self):
            super(MyForm, self).full_clean()
            if self.cleaned_data.get('film') and 'director' in self._errors:
                del self._errors['director']
    
    0 讨论(0)
  • 2020-12-30 06:58

    The easiest approach would be to define your own method for validating the form, like this:

    class MyForm(forms.ModelForm):
        class Meta:
            model = WhateverModel
    
        def clean(self):
            super(MyForm, self).clean() #if necessary
            if self.cleaned_data.get('film') and 'director' in self._errors:
                del self._errors['director']
            return self.cleaned_data                            
    

    See http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-and-validating-fields-that-depend-on-each-other for a more extensive explanation and http://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-clean-method for how it applies to ModelForms.

    0 讨论(0)
提交回复
热议问题