How do i use validation in admin.py while 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 validation Error it doesn't work and shows error page with Exception Type: Validation Error Exception Value:[u'Bla Bla']
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.
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.
Here's an example:
def clean_name(self): if something: raise forms.ValidationError("Something went wrong") return self.cleaned_data["name"]
you should create a form-
inside your CourseAdminForm:
class CourseAdminForm(forms.ModelForm):
def clean(self):
raise ValidationError("Bla Bla")
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.
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!")
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
精彩评论