get label (verbose_name) text from model to template django 3

Viewed 610

I have this model

class Image(models.Model):
    image = models.ImageField(upload_to=multi_image_path, blank=True, null=True)
    product_id = models.IntegerField()

I want to print this model verbose_name in the templates, example:

enter image description here

I want it to be printed dynamically not manually

UPDATE 1

This method

{{ myobject._meta.verbose_name }}

not working, I'm using django 3.0

I get this error

Variables and attributes may not begin with underscores: 'image.product_id._meta.verbose_name'

1 Answers

I found the solution,

our app layout might look like this:

polls/
    __init__.py
    models.py
    templatetags/
        __init__.py
        poll_extras.py
    views.py

And in your template you would use the following:

{% load poll_extras %}

the app that contains the custom tags must be in INSTALLED_APPS in order for the {% load %} tag to work, like this :

INSTALLED_APPS = [
    'polls'
]

note that you should install your app like this 'polls', if you do 'polls.apps.Poll' then the {% load %} will not work.

After that, in poll_extra.py:

from django import template

register = template.Library()

@register.filter
def label_vb(instance, arg):
    return instance._meta.get_field(arg).verbose_name

then inside your template:

{{ image|label_vb:"porduct_id" }}
Related