django admin.display with mark_safe

ivqmmu1c  于 2023-04-13  发布在  Go
关注(0)|答案(1)|浏览(110)

除了重写admin_list模板标记这条丑陋的道路之外,我有没有可能把HTML放在change_list.html<th>中?
我想在表头的文本样式一点点的观赏乐趣,但它是相当棘手的访问django表头。
我有个想法

@admin.display(description = mark_safe("<b class='bg-danger'>status</b>"))
def get_status(self, obj):
    return obj.status
vsmadaxz

vsmadaxz1#

你完全可以将HTML嵌入到title/th中用于admin列。不要使用admin.display decorator,可以这样尝试:

def get_status(self, obj):
    return obj.status
get_status.short_description = mark_safe("<b class='bg-danger'>status</b>")

你可以在源代码中看到它是如何工作的:https://github.com/django/django/blob/3.2.16/django/contrib/admin/options.py#L860

@staticmethod
def _get_action_description(func, name):
    return getattr(func, 'short_description', capfirst(name.replace('_', ' ')))

def _get_base_actions(self):
    """Return the list of actions, prior to any request-based filtering."""
    actions = []
    base_actions = (self.get_action(action) for action in self.actions or [])
    # get_action might have returned None, so filter any of those out.
    base_actions = [action for action in base_actions if action]
    base_action_names = {name for _, name, _ in base_actions}

    # Gather actions from the admin site first
    for (name, func) in self.admin_site.actions:
        if name in base_action_names:
            continue
            
        # RIGHT HERE IS WHERE IT CREATES THE TEXT FOR THE COLUMN TITLE/TH ELEMENT
        description = self._get_action_description(func, name)
        actions.append((func, name, description))
    # Add actions from this ModelAdmin.
    actions.extend(base_actions)
    return actions

相关问题