社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

random_py_guy

random_py_guy 最近回复了
6 年前
回复了 random_py_guy 创建的主题 » Django 2.1-在模板视图中显示模型元类详细名称

编辑:多米尼克·巴顿找到了一个绝妙的解决方案@ 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>

分页也可以像广告那样工作。