Django - 模板顯示模型verbose_names&objects

[英]Django - Template display model verbose_names & objects


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

我需要在模板中顯示多個模型名稱和對象

Here is my view

這是我的看法

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)
  )

And my template

還有我的模板

{% 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 %}

Of course objs._meta.verbose_name doesn't work

當然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 ?

有沒有辦法訪問這個詳細的名稱,而無需為每個模型創建一個函數或從每個模型的視圖中分配值?

1 个解决方案

#1


12  

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:

為了在模板中訪問它,您現在可能已經注意到Django不允許您使用下划線前綴來訪問模板中的屬性。因此,無需在每個模型上創建模型方法,訪問任何給定對象的詳細名稱的最簡單方法是創建模板標記:

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

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:

不相關,但您的模板中有一個錯誤,因為您嘗試訪問查詢集而不是對象的_meta屬性。所以你的標題行應該看起來像:

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

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2011/09/15/cdf34743f8cd156d4f6e52fc8d3b099a.html



 
粤ICP备14056181号  © 2014-2021 ITdaan.com