简体   繁体   English

Django 管理员 model 字段验证

[英]Django admin model field validation

I am developing a web application using django admin template.我正在使用 django 管理模板开发一个 web 应用程序。 In that application I require a model field validation based on another model field input.在该应用程序中,我需要基于另一个 model 字段输入的 model 字段验证。 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.举个例子,如果用户在file_required model 字段中提供“yes”作为输入值,则 Browsefile model 字段应被视为必填字段。 If the user provided "no" as input value in a file_required model field, Browsefile model field should be considered as optional.如果用户在file_required model 字段中提供“no”作为输入值,则 Browsefile model 字段应被视为可选字段。 Please advise请指教

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".您可以通过设置blank=TrueBrowsefile字段定义为 model 中的可选字段,然后制作一个验证表单来检查您的file_required字段,如果用户提供“是”而没有在Browsefile中输入任何内容,那么您将引发 ValidationError “This field is强制的”。

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:您可以通过检查表单的 cleaned_data 来测试用户输入的值,然后在不需要您设置的条件时执行您想要的操作:

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.并且不要忘记在您的 admin.py class 中放置一个form = YourModelForm YourModelForm。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM