Tuesday, July 20, 2021

Django admin custom data and behaviors with admin class fields and methods



Although the modification of Django admin templates allows you to generate any type of Django admin page layout, it can still fall short for cases where you need to include custom data in Django admin pages (e.g. add data from another model for reference) or override the default CRUD behaviors of Django admin pages (e.g. perform a custom audit trail for delete actions).


from coffeehouse.stores.models import Store


class StoreAdmin(admin.ModelAdmin):

    search_fields = ['city','state']

    def changelist_view(self, request, extra_context=None):

        # Add extra context data to pass to change list template

        extra_context = extra_context or {}

        extra_context['my_store_data'] = {'onsale':['Item 1','Item 2']}

        # Execute default logic from parent class changelist_view()

        return super(StoreAdmin, self).changelist_view(

            request, extra_context=extra_context

        )

    def delete_view(self, request, object_id, extra_context=None):

        # Add custom audit logic here

        # Execute default logic from parent class delete_view()

        return super(StoreAdmin, self).delete_view(

            request, object_id, extra_context=extra_context

        )

admin.site.register(Store, StoreAdmin)


In this case, the changelist_view() method  is triggered whenever you visit the list view page of the Store model in the Django admin 

Notice the changelist_view() method adds a custom value to the extra_context variable which is then returned as part of the response, in this case it's a hard-coded value, but you can equally add any type of data like a model query or 3rd party API call to pass to the Django admin page. Because of this last workflow, the list view page of the Store model (i.e. the change_list.html template) can gain access to custom data to display as part of the page.



The delete_view() method in listing 11-24 is triggered whenever you delete a Store model in the Django admin. In this case, the delete_view() method in listing 11-24 simply triggers the default action of deleting a record by calling the parent class's delete_view() method, but you can see how it's possible to execute custom logic (e.g. create an audit trail) whenever a delete action if performed on a Store model in the Django admin.



References:

https://www.webforefront.com/django/admincustomlayout.html

No comments:

Post a Comment