gabse15
gabse15

Reputation: 5

Django admin form validation

In my django app, I want to add a validation to the automatically generated admin form of a model. I want to raise a ValidationError if the attribute title equals "test". I have tried the following in admin.py, but nothing happens if the title is "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)

Upvotes: 0

Views: 6548

Answers (1)

nik_m
nik_m

Reputation: 12086

You have not register the MyModel model with the MyModelAdmin class. 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. No need for clean().

Example:

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

Upvotes: 2

Related Questions