Showing Alert Message Before Saving Model in Django Admin

Viewed 6313

There are ways to show a message after a model has been saved in the database or if there is any error while saving. But how do I show an alert when the user clicks save button in Django Admin? Is there a way to do that?

2 Answers

But how do I show an alert when the user clicks save button in Django Admin? Is there a way to do that?

It's called validation. Django best practice is making validation on the server and this way described in the docs.

You need to do following steps:

  1. Set form in you admin model.
  2. Define clean_name method in your new form, where name is a name of the field which you want to check. You can also overwrite whole clean.
  3. If there's a error then raise a ValidationError to send message to the user. If you raise exception in clean_name method name field will be highlighted in an interface.

from django.core.exceptions import ValidationError
from django import forms
from django.contrib import admin


class ArticleAdmin(admin.ModelAdmin):
    form = MyArticleAdminForm


class MyArticleAdminForm(forms.ModelForm):
    def clean_name(self):
        if some_condition:
            raise ValidationError("Message which you want to show to the user")
        return self.cleaned_data["name"]
Related