Login

Tag "list_display"

Snippet List

Allow foreign key attributes in list_display with '__'

This snippet provides a subclass of admin.ModelAdmin that lets you span foreign key relationships in list_display using '__'. The foreign key columns are sortable and have pretty names, and select_related() is set appropriately so you don't need queries for each line. EDITS: * Fixed error when DEBUG=False. * Broke out `getter_for_related_field` so you can override short_description manually (see example). * Added regular foreign key fields to select_related(), since this is overriding the code in ChangeList that usually does it.

  • admin
  • foreign-key
  • list_display
Read More

Dynamically insert or append a value to an admin option, e.g. list_display or list_filter

You can use this function to change an admin option dynamically. For example, you can add a custom callable to *list_display* based on request, or if the current user has required permissions, as in the example below: class MyAdmin(admin.ModelAdmin): list_display = ('__unicode__', 'other_field') def changelist_view(self, request, extra_context=None): if request.user.is_superuser: add_dynamic_value(self, 'list_display', my_custom_callable) return super(MyAdmin, self).changelist_view(request, extra_context)

  • admin
  • list_display
  • list_filter
Read More

DRY custom ModelAdmin.list_display methods with a decorator

If you add a lot of custom `ModelAdmin` methods to `list_display` like I do, you know it can require a lot of repetition. Notice how adding 'checkbox' to `list_display` requires typing the method name 4 times: class ExampleAdmin(admin.ModelAdmin): list_display = ['checkbox', '__str__'] def checkbox(self, object): return '<input type="checkbox" value="%s"/>' % object.pk checkbox.short_description = mark_safe('&#x2713;') checkbox.allow_tags = True Using this decorator, the name only needs to be typed once: class ExampleAdmin(admin.ModelAdmin): list_display = ['__str__'] @add(list_display, mark_safe('&#x2713;'), 0, allow_tags=True) def checkbox(self, object): return '<input type="checkbox" value="%s"/>' % object.pk

  • admin
  • modeladmin
  • list_display
Read More

4 snippets posted so far.