简体   繁体   English

Django管理表单验证

[英]Django admin form validation

In my django app, I want to add a validation to the automatically generated admin form of a model. 在我的django应用中,我想向模型的自动生成的管理表单添加一个验证。 I want to raise a ValidationError if the attribute title equals "test". 如果属性title等于“ test”,我想引发ValidationError I have tried the following in admin.py , but nothing happens if the title is "test". 我已经在admin.py尝试了以下admin.py ,但是如果标题为“ test”,则什么也不会发生。 Could anyone help, please? 有人可以帮忙吗?

from django.contrib import admin
from django.forms import ModelForm, ValidationError

from .models import MyModel

class MyModelAdminForm(ModelForm):
    class Meta:
        model = MyModel
        fields = '__all__'

    def clean(self):
        cleaned_data = super().clean()
        title = cleaned_data.get('title')
        if title == 'test':
            raise forms.ValidationError('invalid!')
        return cleaned_data

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelAdminForm

admin.site.register(MyModel)

You have not register the MyModel model with the MyModelAdmin class. 您尚未使用MyModelAdmin类注册MyModel模型。 You do that with: 您可以这样做:

admin.site.register(MyModel, MyModelAdmin)

Also, because the clean method checks only one field ( title ), you should use the method clean_title and raise the ValidationError inside there. 另外,由于clean方法仅检查一个字段( title ),因此您应该使用方法clean_title并在其中引发ValidationError No need for clean() . 不需要clean()

Example: 例:

def clean_title(self):
    title = self.cleaned_data['title']
    if title == 'test':
        raise forms.ValidationError('invalid!')
    return title

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

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