Django - Template display model verbose_names & objects

后端 未结 3 1885
暗喜
暗喜 2020-12-31 20:08

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

Here is my view

def contents(request):
  \"\"\"Lists contents\"\"\         


        
3条回答
  •  遥遥无期
    2020-12-31 20:38

    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
    

    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 %}
        
    {% get_verbose_name obj %}
    {% endwith %}

提交回复
热议问题