如何在重写 save_model() 函数时在 admin.py 中使用验证?
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)
当我提出验证错误时,它不起作用并显示错误页面 异常类型:验证错误 异常值:[u'Bla Bla']
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']
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在自定义
ModelForm
中进行验证,然后告诉您的ModelAdmin
使用该表单。Django 文档的这一部分 应该可以帮助你。
Do your validation in a custom
ModelForm
, then tell yourModelAdmin
to use that form.This part of the Django Documentation should help you out.
根据 模型管理方法 上的 django 文档, save_model() 必须保存对象无论如何。您仅使用此方法在保存之前执行额外的处理。我同意 Wogan 的观点,您应该创建一个自定义 ModelForm 并覆盖其 clean() 方法并在那里引发错误。
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:
创建一个表单:
您应该在 CourseAdminForm 中
you should create a form-
inside your CourseAdminForm:
您可以使用类似的内容,
它将被保存,但用户可以看到有什么问题。
You can use something like that
it will be saved but user can to see that something is wrong.
最简单的方法,无需创建自定义表单然后使用它:
1.在您的 Models.py 中添加“blank=True”,例如:
2.创建或添加到 Models.py 同一类中的现有 Clean 方法(不在 Admin.py 中)您想要的字段的验证,例如:
Easiest way to do it, without creating a custom form and then using it:
1.In Your Models.py add "blank=True" for example:
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:
您应该以自定义形式编写验证逻辑,这是一个完整的示例:
You should write validation logic in custom form, here is a complete example: