Django web framework ships with very powerful admin interface for site managers. Default interface is generated from model's metadata and can be customized using many hooks. This presentation is about customizing and making admin interface faster and more user friendly.
16. Customizing objects list: search_fields
● Model field
● Foreign key attribute lookup
● Operators
○ ^ to match starting at the beginning of the field
○ = for case-insensitive exact matching
○ @ operator to perform a full text match
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
list_display = ['title', 'publish_date']
empty_value_display = '(unknown)'
list_filter = ['section', PublishedListFilter]
date_hierarchy = 'publish_date'
search_fields = ['title']
21. Default edit interface
● Default buttons
○ Delete
○ Save and add another
○ Save and continue editing
○ Save
● save_as option: if set to True “Save as new” replaces “Save and add
another” button
22. Customizing edit interface: fields
● fields option
○ List of fields in model edit form
○ Change order
○ Group in same line
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
fields = [
'author',
('title', 'lead_text'),
'content',
('publish_date', 'image'),
'section'
]
24. Customizing edit interface
● exclude option
○ List of fields not shown in edit form
● readonly_fields option
○ Field or method
● fieldsets option
○ Group fields
● form option
○ Replace default Form with custom
● view_on_site option
○ Boolean - calls get_absolute_url
○ Callable
25. Customizing edit interface: many to many
● filter_horizontal option
● filter_vertical option
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
…
filter_horizontal = ['section']
29. Customizing admin interface: actions
● Functions that get called with a list of objects selected on the change list page
● Simple logic: use function
● Complex logic: redirect the user to another view in function
def delete_publish_date(modeladmin, request, queryset):
queryset.update(publish_date=None)
delete_publish_date.short_description = "Delete published
date for selected articles"
@admin.register(Article)
class ArticleAdmin(admin.ModelAdmin):
…
actions = [delete_publish_date]
31. Optimization
● show_full_result_count option in list view
○ Eliminates expensive count
● list_select_related option in list view
○ Django will use select_related in query
● raw_id_fields option in edit view
32. There is more
● Overriding default templates
● Overriding methods
● History view
● Decorator @staff_member_required