Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing Alert Message Before Saving Model in Django Admin

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?

like image 978
QuestionEverything Avatar asked Nov 02 '25 04:11

QuestionEverything


2 Answers

If you explored the django admin then you can see that django uses submit_line.html for rendering the save ( save & continue ) buttons.

There are multiple ways to do it,

1 ) If you want app wise alerts, then in your admin.py file include the custom js file with admin media option,

@admin.register(Model)
class ModelAdmin(admin.ModelAdmin):
   class Media:
        js = (
            'js/myscript.js',  # project's static folder ( /static/js/myscript.js )
        )

In your myscript.js write,

window.addEventListener("load", function () {
(function ($) {
    $('form').submit(function () {
        var c = confirm("continue submitting ?");
        return c;
    });


})(django.jQuery);

}); 2 ) If you want alerts for all the forms in admin just inherit submit_line.html in templates/admin/submit_line.html directory and simply write,

<script>
    $(document).ready(function(){
        $('form').submit(function() {
            var c = confirm("continue submitting ?");
            return c;
        });
    })
</script>
like image 66
Aniket Pawar Avatar answered Nov 04 '25 18:11

Aniket Pawar


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"]
like image 29
Daniil Mashkin Avatar answered Nov 04 '25 18:11

Daniil Mashkin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!