Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making Django Signals Specific To Admin Save ONLY

Tags:

python

django

I am currently working on a Django website. I would like to figure out how to make a post_save signal that is activated ONLY when I save from Django Admin.

Right now, I have made a post_save function. This works for all intents and purposes, but another part of my code uses .save() to update an Integer within the main Event model (the integer represents the number of books submitted).

I update the number of books submitted upon users loading the Event page.

This causes extremely long load times when users try to access a page with all previous events since it runs my "book_organizer" function for every item on the page when I only need it to run when I update and save event details directly from the admin page.

@receiver(post_save, sender=Event)
def save_post(sender, instance, **kwargs):

    if instance.books_read==True:

        book_organizer.organize_it(instance)

post_save.connect(save_post, sender=Event)

What I would like to do, is make it so that my current save_post function runs ONLY when I hit the "Save" button from Django admin.

I would like to avoid overriding the save function as I read that it is not recommended.

Solved: For future reference, the solution suggested by the accepted answer worked like a charm. I was able to isolate save instances from Django Admin Dashboard.

like image 781
LearnIT Avatar asked May 04 '19 03:05

LearnIT


Video Answer


1 Answers

I am not sure., this is the recommended approach, but what you can do is to create a custom ModelAdmin with save_model function in admin.py

class FoobarModelAdmin(ModelAdmin):

    def save_model(self, request, obj, form, change):
        obj.from_admin_site = True #here we setting instance attribute which we check in `post_save`
        super().save_model(request, obj, form, change)

admin.site.register(Foobar, FoobarModelAdmin)

then we can check in post_save signal that from_admin_site attr is set or not. if set then it is saved from the admin site.

@receiver(post_save, sender=Event)
def save_post(sender, instance, **kwargs):
    if getattr(instance, 'from_admin_site', False):
        // Todo
like image 109
Hari Avatar answered Sep 20 '22 20:09

Hari