brsbilgic
brsbilgic

Reputation: 11833

Django admin return custom error message during model saving

I would like to return some custom error messages in save_model function of Django admin page.

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()

Of course, Else part isn't correct but I want to illustrate what I want.

I am glad to suggest me a way or document to do that. Thanks

Upvotes: 8

Views: 15040

Answers (2)

Brandon Taylor
Brandon Taylor

Reputation: 34553

You need to use a form to do your validation in your 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)

Hope that helps you out.

Upvotes: 15

Kix Panganiban
Kix Panganiban

Reputation: 15

I'm using Django 1.6.3, and I'd like to add to Brandon's answer.

Add admin.site.register(Employer, EmployerAdmin) as a separate line below the EmployerAdmin class; that is, below form = EmployerAdminForm, unindented.

It took me some time to figure out why Brandon's answer wasn't working for me and the validations weren't running, apparently, you just need to register it on admin first.

Cheers.

Upvotes: 0

Related Questions