The Django admin feature is great for quickly spinning up basic CRUD actions without giving someone direct database access, but gives you very little control over the feature set or content. This is perfect for quickly spinning up the ability to create or update rows in the database, but sometimes you need just a little more.
In my case, I was creating a template for a PDF that I wanted to be preview-able directly from the admin page where the template was created, so people could see what the result would be of the object they’d just created. Django admin has a
view_on_site feature that I considered using, but it uses the model’s
get_absolute_url method, which would mean redirecting the user off of the admin site entirely to the actual application — I didn’t want my admin users to possibly have to reauthenticate on the main site when they’d already authenticated on the admin site.
I really just needed a single link with a view that would show a PDF for me, but even something that basic is not immediately obvious in Django admin. Let’s take a look at how to do it! As always, here are the docs for Django admin — this post assumes you’ve already got a basic Django admin site set up and are just looking to add a bit of customization to it.
Your admin site has a
get_urls method that doesn’t need overwriting if you just want a page for each admin page you’ve registered. But adding our own custom view to preview our template is a great example of where we’ll need to add to this:
from django.conf.urls import url
from django.contrib import adminclass CustomAdminSite(admin.AdminSite):
urls = super(CustomAdminSite, self).get_urls()
custom_urls = [
url(r'desired/path$', self.admin_view(organization_admin.preview), name="preview"),
return urls + custom_urls
admin_view is explained in the docs linked above, but in short, it’s a wrapper that:
- Means authentication is enforced on the view
- Means the view will not be cached
Now that we’ve created a url, we need to create the view that it will send a user to when visited.
preview view does the logic to render the PDF I want to preview and returns an HttpResponse with
content_type='application/pdf', this isn’t…