Home > Net >  Django admin model field validation
Django admin model field validation

Time:05-20

I am developing a web application using django admin template. In that application I require a model field validation based on another model field input. Lets say an example, If the user provided "yes" as input value in a file_required model field, Browsefile model field should be considered as mandatory field. If the user provided "no" as input value in a file_required model field, Browsefile model field should be considered as optional. Please advise

CodePudding user response:

You can define your Browsefile field as optional in your model by setting blank=True and then make a validation form to check your file_required field, and if the user provided "yes" without entering anything in Browsefile then you raise a ValidationError "This field is mandatory".

You can test the user inputted values by checking the cleaned_data of your form and then do what you want if the condition you set are not required :

class YourModelForm(forms.ModelForm):
    def clean(self):
        file_required = self.cleaned_date['file_required']
        if file_required == "yes" and not self.cleaned_data['Browsefile']:
            raise forms.ValidationError({'Browsefile': "This field is mandatory"})

And don't forget to put a form = YourModelForm in your admin.py class.

  • Related