Django管理员在模型保存期间返回自定义错误消息

时间:2011-07-25 19:20:10

标签: django django-admin admin

我想在Django管理页面的save_model函数中返回一些自定义错误消息。

class EmployerAdmin(admin.ModelAdmin):
  exclude = ('update_user','updatedate','activatedate','activate_user')

  def save_model(self, request, obj, form, change):
    if obj.department != None and obj.isDepartmentSuggested:
        obj.isDepartmentSuggested =False
    else:
       return "You don't set a valid department. Do you want to continue ?"

    obj.update_user = request.user
    obj.updatedate = datetime.datetime.now()
    obj.save()

当然,Else部分不正确,但我想说明我想要的内容。

我很高兴为我建议一种方法或文件。 感谢

2 个答案:

答案 0 :(得分:10)

您需要使用表单在EmployerAdmin中进行验证:

#forms.py
from your_app.models import Employer

class EmployerAdminForm(forms.ModelForm):
    class Meta:
        model = Employer

    def clean(self):
        cleaned_data = self.cleaned_data
        department = cleaned_data.get('department')
        isDepartmentSuggested = cleaned_data.get('isDepartmentSuggested')
        if department == None and not isDepartmentSuggested:
            raise forms.ValidationError(u"You haven't set a valid department. Do you want to continue?")
        return cleaned_data

#admin.py
from django.contrib import admin
from your_app.forms import EmployerAdminForm
from your_app.models import Employer

class EmployerAdmin(admin.ModelAdmin):
    exclude = ('update_user','updatedate','activatedate','activate_user')
    form = EmployerAdminForm

admin.site.register(Employer, EmployerAdmin)

希望能帮到你。

答案 1 :(得分:0)

我使用的是Django 1.6.3,我想补充布兰登的答案。

admin.site.register(Employer, EmployerAdmin)添加为EmployerAdmin类下方的单独行;也就是说,低于form = EmployerAdminForm,未缩进。

我花了一些时间弄清楚为什么Brandon的回答并不适合我并且验证没有运行,显然,你只需要先在管理员面前注册。

干杯。