How to use validation in admin.py when overriding save_model () function?

Admin.py class CourseAdmin(admin.ModelAdmin): list_display = ('course_code', 'title', 'short' ) def save_model(self, request, obj, form, change): import os #obj.author = request.user dir_name = obj.course_code path = settings.MEDIA_ROOT +os.sep+'xml'+os.sep+dir_name #if user updates course name then course would be renames if change: dir_name = Course.objects.get(pk=obj.pk).course_code src = settings.MEDIA_ROOT +os.sep+'xml'+os.sep+dir_name os.rename(src,path) else: if not os.path.exists(path): os.makedirs(path) obj.save() else: raise ValidationError('Bla Bla') admin.site.register(Course, CourseAdmin) 

when I raise the check. The error does not work and shows the page with the type of exception: error checking Exceptional value: [u'Bla Bla ']

+6
django django-admin
source share
6 answers

According to django's documentation on model administration methods, save_model () should save the object no matter what. This method is only used to perform additional processing before saving. I agree with Wogan, you should just create a custom ModelForm and override its clean () method and raise an error there.

+7
source share

Do your validation in a custom ModelForm and then say << 21> to use this form.

This part of the Django Documentation should help you.

+4
source share

Here is an example:

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

you have to create a form -

inside your CourseAdminForm course:

 class CourseAdminForm(forms.ModelForm): def clean(self): raise ValidationError("Bla Bla") 
0
source share

You can use something like this

 from django.contrib import messages messages.error(request, '<Your message>') 

it will be saved, but the user will be able to see that something is wrong.

0
source share

The easiest way to do this is 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 an existing Clean method in the same Model.py class (not in Admin.py) confirmation in the required field, for example:

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

All Articles