user3000605
user3000605

Reputation: 11

Django admin show success message when saving model

I'm new to django and trying to get a success message to show when I save a form in the admin. I want it to show at the top of the page which lists all items for the model (changelist page I think).

I've had a look through several posts here and the django documentation and worked out I need to use the messages framework and overwrite the save_model method in my model admin, here's what I have so far:

class scoutGroupAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        messages.add_message(request, messages.INFO, 'Hello world.')
        super(scoutGroupAdmin,self).save_model(request, obj, form, change)

I've tried multiple versions of the above but no matter what I do when I go back to the changelist page there is no message displayed. Again I'm just learning django so please let me know if I'm missing something obvious !

Thanks

Upvotes: 1

Views: 2810

Answers (2)

Add "obj.save()" and remove "super()" as shown below:

class scoutGroupAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        obj.save() # Here
        messages.add_message(request, messages.INFO, 'Hello world.')
        # super(scoutGroupAdmin,self).save_model(request, obj, form, change)

Upvotes: 0

Wellington Gomes
Wellington Gomes

Reputation: 56

Try the following:

class scoutGroupAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        messages.add_message(request, messages.INFO, 'Hello world.')
        obj.save()

Do not call "super". The "obj" is the instance to be saved. The "change" is a boolean that tells you if the instance is being created or changed.

See the docs: django.contrib.admin.ModelAdmin.save_model

Upvotes: 1

Related Questions