[Fixed]-How do i use validation in admin.py while overriding save_model() function?

9👍

As per django documentation on model admin methods, the save_model() Must save the object no matter what. You only use this method for performing extra processing before save. I agree with Wogan, you should just create a custom ModelForm and override its clean() method and raise the error there.

13👍

Do your validation in a custom ModelForm, then tell your ModelAdmin to use that form.

This part of the Django Documentation should help you out.

👤Wogan

6👍

Here’s an example:

def clean_name(self):
    if something:
        raise forms.ValidationError("Something went wrong")
    return self.cleaned_data["name"]
👤Asdf

6👍

you should create a form-

inside your CourseAdminForm:

class CourseAdminForm(forms.ModelForm):

    def clean(self):
        raise ValidationError("Bla Bla") 

3👍

You can use something like that

from django.contrib import messages

messages.error(request, '<Your message>')

it will be saved but user can to see that something is wrong.

3👍

Easiest way to do it, without creating a custom form and then using it:

1.In Your Models.py add “blank=True” for example:

Zone_Name = models.CharField(max_length=100L,unique=True,blank=True )

2.Create or add to an existing Clean method in the same class of Models.py (not in Admin.py) the validation on the field that you want, for example:

def clean(self):
         if self.Zone_Name == None or not self.Zone_Name :
            raise ValidationError("Zone name is not given!")

3👍

You should write validation logic in custom form, here is a complete example:

# Created by BaiJiFeiLong@gmail.com at 2022/4/26
from django import forms
from django.contrib import admin
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError


class UserAdminForm(forms.ModelForm):
    # Show error on username field
    def clean_username(self):
        username = self.cleaned_data.get("username")
        if len(username) <= 6:
            raise ValidationError("Username is illegal")
        return username

    # Show error on form top
    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data.get("username") == cleaned_data.get("password"):
            raise ValidationError("Password must not be equal to username")
        return cleaned_data


class UserAdmin(admin.ModelAdmin):
    model = User
    form = UserAdminForm

Leave a comment