user7120561
user7120561

Reputation:

How to get the name of a class model in template django

This question is similar to this question (Model name of objects in django templates) but not the same.

I want to know how gets the Models class name (in this case 'Apple'), or at the very least return a string that I can pass over.

Model.py

   django.db import models
   class Apple(models.Model):
      .....

apple.html

 <p>Sorry, no {{ ***Model class name**** }}</p>

An example in the browser::: " Sorry, no Apple "

EDIT

Some extra conditions:

  1. What if there is no object created from the model, hence the 'Sorry, no apples'
  2. How to kind this flexible so you can use the same template for any kind of fruit.

Upvotes: 2

Views: 3031

Answers (1)

NS0
NS0

Reputation: 6116

If you're passing an object to your template, and you want to do this processing in the template and not in the views, one approach is to create the following template tag:

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

and get the name with

{{apple|get_class}}

Upvotes: 5

Related Questions