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?
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>
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:
form in you admin model.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. 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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With