Django - verbose_name from a template tag

纵然是瞬间 提交于 2019-12-10 11:18:39

问题


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

Here is my view

def contents(request):
  """Lists Objects"""
  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)
  )

My template

{% for objs in objects %}
  <div class="object">
    <div class="object_name">{{ get_verbose_name objs.0 }}</div>
    <ul>
    {% for obj in objs %}
      <li>{{ obj }}</li>
    {% endfor %}
    </ul>
  </div>
{% endfor %}

And my template filter

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

This works only if there is at least one obj for each Model in the database.
How can I get the verbose name of each Model if there is no data ?


回答1:


You are trying to get a model from the first object in the list. This way, if this object does not exist, you won't get anything.

Try to use a query set instead:

{{ get_verbose_name objs }}

@register.simple_tag
def get_verbose_name(queryset):
  return queryset.model._meta.verbose_name_plural


来源:https://stackoverflow.com/questions/7792353/django-verbose-name-from-a-template-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!