编辑:多米尼克·巴顿找到了一个绝妙的解决方案@
https://blog.confirm.ch/accessing-models-verbose-names-django-templates/
首先,在应用程序级别创建一个templatags文件夹,并填充一个init文件。接下来,创建一个模板标记文件。像verbose.py之类的。
from django import template
register = template.Library()
@register.simple_tag
def verbose_name(value):
#Django template filter which returns the verbose name of a model.
#Note: I set my verbose_name the same as the plural, so I only need one tag.
if hasattr(value, 'model'):
value = value.model
return value._meta.verbose_name
接下来,应该修改ListView。
from django.views.generic.list import ListView as DjangoListView
from .models import MyTestModel
class ListView(DjangoListView):
#Enhanced ListView which includes the `model` in the context data,
#so that the template has access to its model class.
#Set normally
model = MyTestModel
template_name = 'base.html'
context_object_name = 'model_list'
ordering = ['record']
def get_context_data(self):
#Adds the model to the context data.
context = super(ListView, self).get_context_data()
context['model'] = self.model
return context
不要忘记将路径添加到url.py:
path('your_extension/', views.ListView.as_view(), name='base')
最后,加载标记并正常遍历“记录”:
{% load verbose %}
<h1> {% verbose_name model%} </h1>
<ul style='list-style:none'>
{% for item in model_list %}
<li>{{ item }}}</a></li>
{% endfor %}
</ul>
分页也可以像广告那样工作。