You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django ListView中访问model属性并在模板中使用?

Django ListView中访问Model属性实现动态表头与标题

你的思路是对的,通过向上下文添加model相关信息就能实现需求,下面给你两种实用方案:

方案一:重写get_context_data传递Model信息

直接在视图里把model对象、字段名/友好名称传入模板上下文:

# views.py
class ExampleListView(ListView):
    model = Example

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # 传入model对象
        context['model'] = self.model
        # 获取所有字段名(可自行过滤id等自动生成字段)
        context['field_names'] = [field.name for field in self.model._meta.fields]
        # 获取字段的友好显示名(比字段名更适合做表头)
        context['field_labels'] = [field.verbose_name for field in self.model._meta.fields]
        return context

模板中使用上下文变量

首先需要注册一个自定义过滤器来动态获取对象属性(Django默认没有这个过滤器):

在你的app目录下创建templatetags文件夹,新建custom_filters.py:

from django import template

register = template.Library()

@register.filter
def get_attr(obj, attr_name):
    return getattr(obj, attr_name)

然后在模板中加载过滤器并使用:

{% load custom_filters %}

{% block content %}
<!-- 动态生成标题,用model的复数友好名称 -->
<h2>{{ model._meta.verbose_name_plural|title }}</h2>
<table>
    <thead>
      <tr>
         <!-- 遍历友好字段名作为表头 -->
         {% for label in field_labels %}
             <th>{{ label|title }}</th>
         {% endfor %}
      </tr>
    </thead>
    <tbody>
        {% for item in object_list %}
        <tr>
           <!-- 动态获取每条记录的字段值 -->
           {% for field in field_names %}
               <td>{{ item|get_attr:field }}</td>
           {% endfor %}
        </tr>
        {% endfor %}
    </tbody>
</table>
{% endblock %}

方案二:利用ListView自带上下文变量(仅标题)

ListView默认会把model的verbose_name和verbose_name_plural传入上下文,如果你只需要动态标题,可以直接用:

{% block content %}
<h2>{{ verbose_name_plural|title }}</h2>
<!-- 表头部分还是需要方案一的方式实现 -->
{% endblock %}

内容的提问来源于stack exchange,提问作者Stephan Daniels

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 11:42:43