How to give a column in the Django admin change_list a CSS class

后端 未结 3 1967
梦如初夏
梦如初夏 2021-01-06 09:44

I\'d like to change the column widths in the list display of the Django admin.

Is it possible somehow to add a CSS classname to a column? I\'d preferably not overwri

相关标签:
3条回答
  • 2021-01-06 10:35

    While this feature is implemented in vers1.6 as StvnW said, for earlier versions you can do the following:

    In admin.py:

    class MyModelAdmin(admin.ModelAdmin):
        # your code here
    
        # specify a stylesheet just for the list view
        class Media:
            css = {'all': ('css/mymodel_list.css')}
    

    In mymodel_list.css:

    /* replace '5' with the column desired */
    table#result_list td:nth-child(5) {
        width: 15em;
    }
    

    Specifying table#result_list will apply this stylesheet only to the list view and won't affect the normal admin page for this model. Also, note that while django uses th for the first column of the model, it still counts for a td child.

    0 讨论(0)
  • 2021-01-06 10:46

    There is an open ticket that addresses the need for specifying css classes for table columns in the change_list view.

    That said ... in the description for the ticket there's a snippet that injects a custom stylesheet in your change_list-template:

    {% extends "admin/change_list.html" %}
    {% block extrastyle %}
      {{ block.super }}
      <link rel="stylesheet" type="text/css" href="/css/poll_admin_changelist.css" />
    {% endblock extrastyle %}
    

    So you don't override the whole template, only the part (extrastyle) you need.

    Now you could inject your own stylesheet and for example style your columns using the :nth-child-selector

    Another option would be to wrap your specific fields in html which can be done using the list_display option. Here you could define a width or class for a wrapped element. This does only makes sense though, if you want to control the width of limited set of fields

    0 讨论(0)
  • 2021-01-06 10:48

    In Django >= 1.6, CSS classes are included with list_display output:

    "The field names in list_display will also appear as CSS classes in the HTML output, in the form of column-<field_name> on each <th> element. This can be used to set column widths in a CSS file."

    0 讨论(0)
提交回复
热议问题