Extending Django Admin Templates - altering change list

前端 未结 3 2114
深忆病人
深忆病人 2020-12-02 15:52

A (not so) quick question about extending django admin templates.

I\'m trying to change the result list (change list in django lingo) of a specific model by adding

3条回答
  •  执笔经年
    2020-12-02 16:35

    Step 1: Overriding changelist view:
    You'll have to override a template as opposed to specifying one like you can with add_view / change_view.

    First things first, override def changelist_view(self, request, extra_context=None): in your ModelAdmin. Remember to call super(foo, self).changelist_view(request, extra_context) and to return that.

    Step 2: Overriding templates:
    Next, override the app-specific changelist template at templates/admin/my_app/my_model/change_list.html (or not.. you can use a global changelist override too if you'd like).

    Step 3: Copy result list functionality
    I think you can either copy result_list functionality (define a new template tag) or fake it by copying and pasting the result_list function and template include into your view.

    # django.contrib.admin.templatetags.admin_list
    def result_list(cl):
        """
        Displays the headers and data list together
        """
        return {'cl': cl,
                'result_hidden_fields': list(result_hidden_fields(cl)),
                'result_headers': list(result_headers(cl)),
                'results': list(results(cl))}
    result_list = register.inclusion_tag("admin/change_list_results.html")(result_list)
    

    You can see the admin uses this admin/change_list_results.html template to render individual columns so you'll need to use one of the methods to replace this template tag.

    Since it's looking for a global template, I wouldn't override it.

    Either define a new tag w/ new template specifically for your view, or send result_list(cl) to your template directly and adopt the admin/change_list_results.html for use directly in your change_list.html template.

提交回复
热议问题