[PYTHON] Django admin screen reverse lookup memo

List screen (Change List View)

Specify the item to be displayed

ModelAdmin.list_display = ('hoge',)

Custom method of Model that returns Bool can be specified directly. You can also specify __unicode__ or __str__.

ModelAdmin.list_display = ('__str__', 'model_custom_method')

Specify the item to put the link to the detail screen

By default, the one displayed on the far left has a link

ModelAdmin.list_display = ('hoge', 'fuga')
ModelAdmin.list_display_links = ('fuga',)

Show custom values

ModelAdmin.list_display = ('custom_hoge',)

def custom_hoge(self, obj):
    return u'Hoge'
custom_hoge.short_description = u'Display name'
custom_hoge.allow_tags = True  #html tag permission

For user input, use the format_html ('hoge') function to escape.

Default sort order

ModelAdmin.ordering = ('created_at',)  #Sort by creation time

Custom action (the one in the select part at the top of the list view)

ModelAdmin.actions = ['hoge']  #List defined functions etc.
ModelAdmin.actions_on_top = True  #Displayed at the top of the page
ModelAdmin.actions_on_bottom = True  #Displayed at the bottom of the page

Sort custom fields

All Django sorts are done at the DB query level, so you can't sort fields that don't actually have columns in the DB. However, when a custom field is a substitute for a certain field, you can sort it by specifying the field name.

ModelAdmin.list_display = ('number_str',)

#number is a number(int)To return
def number_str(self, obj):
    return str(obj.number)
number_str.admin_order_field = 'number'

How to make a custom field with no columns in the DB sortable with list_display

StackOverflow Django admin: how to sort by one of the custom list_display fields that has no database field

Addition / change screen

I want to update a specific field

There are two specification methods


  1. fields can also specify the value of ModelAdmin.readonly_fields, but cannot be edited
  2. Unlike list_display etc., you can only specify the field of Model or ModelAdmin.form
ModelAdmin.fields = ('hoge', 'fuga')  # hoge,Only the fuga field is added and edited when updating
ModelAdmin.fields = (('hoge', 'fuga'), 'piyo')  # hoge,fuga is displayed on the same line


ModelAdmin.exclude = ('hoge',)  #hoge is not editable

Foreign key values can also be added / edited on the same screen

#Define Inline model
class SomeForeignKeyModelInline(admin.TabularInline):
    model = SomeForeignKeyModel

#Add to the management screen of the model you want to display the Inline model
class HogeAdmin(admin.ModelAdmin):
    list_display = ('hoge', 'fuga')
    inlines = [SomeForeignKeyModelInline]

Rich screen with fieldsets option

ModelAdmin.fieldsets = (
    ( 'name', {'Option name': ('Option value',)} ),
    (None, {
        'fields': ('hoge', 'fuga')

Custom form

By default, ModelForm will generate a nice form for the admin screen, but you can also specify your own custom form.

ModelAdmin.form = HogeForm

I want to display a custom form field that is not defined in the model on the management screen

stackOverflow: django admin - add custom form fields that are not part of the model

I want to customize an existing auto-generated form

Hook with the get_form method

ModelAdmin.get_form(request, obj=None, **kwargs)

Overwrite management screen template


The original template of the management screen is stored in contrib / admin / template / admin. To overwrite, add ʻadmin /to the directory set byTEMPLATE_DIR`.

Add the management target you want to overwrite under the above directory with ʻapp_name / modelname /`. The template below the app name is applied to all models under the app. Templates below the model name are applied only to the management screen of that model. Directory names are all lowercase.

Template creation policy

Basically, it is more efficient to overwrite only the necessary parts.

Example: When you want to overwrite the fuga model list screen of the hoge app Create ʻadmin / hoge / fuga / change_list.html`.

After that, overwrite the {% block%} you want to change as follows.

{% extend 'admin/change_list.html' %}
{% block 'content' %}
Forms, variables, etc. that you want to add
{{ block.super }}
{% endblock 'content' %}

Addition of original functions

If you want to add your own function to the management screen, a memo of work that may be necessary


Add a URL that provides your own functionality. You need to customize the URL that the Django admin screen generates by default.

Use get_urls.

from django.conf.urls import url
from django.http import HttpResponse
class HogeAdmin(admin.ModelAdmin):
    def get_urls(self):
        urls = super(HogeAdmin, self).get_urls()
        my_urls = [
            url(r'^hoge/$', self.admin_site.admin_view(self.hoge), name='hoge'),
        return my_urls + urls

    def hoge(self, request):
        return HttpResponse('OK')

self.admin_site.admin_view gives permission check and never_cache to the view you want to add. Basically, it's better to wrap it with this.

Note the order of return my_url + urls. If you do not put my_urls first, the standard URL of the management screen will take precedence. I can't get to the view of my own URL.

Overwrite the operation of the existing management screen

Override the behavior of each View function

class HogeAdmin(admin.ModelAdmin):
    #Example of overwriting the operation of the list screen
    def changelist_view(self, request, extra_context=None):
        extra_context = extra_context or {}
        extra_context['hoge'] = 'hoge'
        return super(HogeAdmin, self).changelist_view(request, extra_context=extra_context)


Manage the same Model with multiple ModelAdmins

StackOverflow Multiple ModelAdmins/views for same model in Django admin

Recommended Posts

Django admin screen reverse lookup memo
Pandas reverse lookup memo
Django admin screen list_filter customization
Django admin screen customization first step
Reverse lookup pytest
Django Learning Memo
django tutorial memo
WEB application development using Django [Admin screen creation]
DJango Memo: From the beginning (Error screen settings)
heroku deployment memo (Django)
Sympy Reverse Lookup Reference
Django2 screen addition flow
Django memo # 1 from scratch
Luigi Reverse Lookup Reference
[Memo] Django development environment
DJango Memo: From the beginning (more edits to the management screen)
When you forget your admin screen username / password in Django
Django development environment construction memo
Tuning your Django admin site
Server setting tips Reverse lookup
My reverse numpy / scipy memo
Create a Django login screen
[Learning memo] Django command summary
DJango memo: From the beginning (using the management screen) my addictive point
The story of failing to update "calendar.day_abbr" on the admin screen of django