Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add custom Django admin action

I'm looking for ways of adding custom actions to a Django admin change page. I am not looking for actions that can be added to the dropdown box in the overview.

One model in my Django application contains information about documents, and those are automatically compiled to PDF files at the frontend. I'd like to give the administrator the possibility to quickly render the PDF directly from the change page to be able to quickly check the results.

I've already played around with overriding change_form.html/submit_line.html, and it's absolutely no problem to add a button. But I wonder how to extend the admin module in a clean way so that it includes my custom action.

like image 558
stschindler Avatar asked Feb 11 '13 12:02

stschindler


People also ask

Can I use Django admin as frontend?

Django Admin's task is to provide an interface to the admin of the web project. Django's Docs clearly state that Django Admin is not made for frontend work.

How do you put a button on the list page for each row in Django admin page?

In the case of a button, you'll want to use format_html . This will mark the relevant parts of the string safe, and so that it's displayed as an HTML button, and escape the other parts to protect against various securit issues. The values of object.id and object. some_property will get inserted into the placeholders.


1 Answers

Since custom admin views are basically just normal views there aren't many specialities. A few things you should consider for a cleaner integration:

  • Add the url pattern through get_urls() of the AdminSite.
  • Provide the current_app argument to RequestContext or Context when rendering a template which subclasses admin templates.

EDIT:

Found a an example here: http://shrenikp.webs.com/apps/blog/show/5211522-add-custom-view-method-for-django-admin-model-

Note, that the example doesn't utilize the current_app argument i've mentioned. I suppose your view to generate the PDF just returns a HttpResponse with the appropriate content type rather than rendering a response with a Context, so it's not needed. All in all the current_app only makes sense when you subclass an admin template used by your custom view which actually makes use of current_app somewhere.

The example encapsulates the urls and view in a ModelAdmin. It is also possible to do this through a AdminSite subclass, but at least in your use case this is probably overkill.

By the way, overriding the change_form.html template for your app to add a button to the standard change view is just fine. There is no special api for this in the admin (unfortunately).

like image 51
Dirk Eschler Avatar answered Sep 19 '22 17:09

Dirk Eschler