Django - Creating a Custom Template Tag to show Model Name

746 Views Asked by At

I have a model:

class Survey(models.Model):
name = models.CharField(max_length = 200)

def __str__(self):
    return self.name

And in my template I want to show the name of the current Survey model:

<h1> {{survey.name |name}} </h1>

I'm using a custom template tag/filter to display that name; however, it is showing as 'str' instead of the name of the current Survey model.

Here is the filter code:

from django import template

register = template.Library()

@register.filter
def name(value):
return value.__class__.__name__

What am I doing wrong here?

3

There are 3 best solutions below

2
Stuart Dines On

When you are calling the template tag with <h1> {{survey.name |name}} </h1> you are passing it the string associated with the model. As the field is a CharField it will return a string and therefore the name of the that class is str.

I believe what you are wanting it <h1> {{survey|name}} </h1> which will send the template tag the instance of Survey and therefore get the class name from that.

0
Mo Hertz On

As an addition to the above answer...

Your filter is calling __class__.__name__, which I believe would return str

Try changing your filter to return value.__name__

See this similar question

0
Sanchit On

you can do something like this:

  • if you have defined verbose_name in meta then you can do:

    return (model-name)._meta.verbose_name

  • otherwise you can do:

    return (model-name).name