March 29, 2015 in Django
Today I was working to continue to improve my website and came across some really helpful stuff to improve the Django admin. By default, the django admin has a really simple interface for managing objects in your database. For example, the page for managing my Pages looks like this
This works and is much nicer than having to build my own admin, but there is a lot more power hidden in Django. You can actually control columns to show in the admin as well as add searching and restrict the pagination. For example, let's look at the page class.
#models.py class Page(models.Model): title = models.CharField(max_length=128) slug = models.SlugField(default='', blank=True, max_length=128) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) content = models.TextField() script = models.TextField(default='', blank=True) style = models.TextField(default='', blank=True) author = models.ForeignKey(User) def __str__(self): return self.title
The Page class has a lot of fields that might be useful for searching in the admin. Let's recall how we register the Page class with the admin
#admin.py from django.contrib import admin from blog.models import Page admin.site.register(Page)
To add the new columns and search capabilities, we simple need to make a ModelAdmin class to tell Django how to display it.
#admin.py from django.contrib import admin from blog.models import Page class PageAdmin(admin.ModelAdmin): list_display = ('id', 'title', 'slug', 'author', 'updated') list_display_links = ('id', 'title') search_fields = ('title', 'content') list_per_page = 25 admin.site.register(Page, PageAdmin)
The list display is a tuple of of all of the items that we want shown in the columns. List display links is a tuple of all of the items that we want to attach links to the edit page from. The search fields are the fields by which we want to be able to search our data and the list per page is how many to show on each page.
By adding this one simple class, we have unlocked some of the hidden power of the Django admin and helped to make the list view more meaningful. Here is what the new admin looks like
Much better. There are plenty more properties that can be changed to make it even more powerful including filtering and more. For more, check out the Django admin documentation.
EDIT: I am using the django flat theme in my admin.