Django - 模板显示模型verbose_names&对象 [英] Django - Template display model verbose_names & objects

查看:76
本文介绍了Django - 模板显示模型verbose_names&对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要显示几个型号名称&模板中的对象

I need to display several models name & objects in a template

这是我的视图

def contents(request):
  """Lists contents"""
  objects = [
    Model1.objects.all(),
    Model2.objects.all(),
    Model3.objects.all(),
    Model4.objects.all(),
  ]
  return render_to_response('content/contents.html', objs
  , context_instance=RequestContext(request)
  )

我的模板

{% for objs in objects %}
  <div class="content">
    <div class="title">{{ objs._meta.verbose_name }}</div>
    <ul>
    {% for obj in objs %}
      <li>{{ obj }}</li>
    {% endfor %}
    </ul>
  </div>
{% endfor %}

当然 objs._meta。 verbose_name 不工作

有没有办法访问这个冗长的名称,而不必为每个模型创建一个函数或分配值得从每个模型的角度来看?

Is there a way to access to this verbose name without having to create a function for each model or to assign the value from the view for each model ?

推荐答案

为了在你的模板中访问它,你可能已经注意到Django没有不要使用下划线前缀从模板访问属性。因此,无需在每个模型上创建模型方法,访问任何给定对象的详细名称的最简单方法就是创建一个模板标签:

For accessing it in your template, you've probably noticed by now that Django doesn't let you use underscore prefixes to access attributes from templates. Thus, the easiest way to access the verbose name for any given object without having to create a model method on each model would be to just create a template tag:

@register.simple_tag 
def get_verbose_name(object): 
    return object._meta.verbose_name

无关,但您的模板中有错误,因为您正在尝试访问查询集上的_meta属性而不是对象。所以你的标题行应该看起来像:

Unrelated, but you have a bug in your template, in that you are trying to access the _meta attribute on a queryset instead of an object. So your title line should instead look something like:

{% with objs|first as obj %}
    <div class="title">{% get_verbose_name obj %}</div>
{% endwith %}

这篇关于Django - 模板显示模型verbose_names&amp;对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆