mpen
mpen

Reputation: 283335

Django: check for generic type in template?

I'm using generic types in my Profile model:

user_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
details = generic.GenericForeignKey('user_type', 'object_id')

But now I want to check if a user is a certain type from within my template. I can get the user type with {{ user.get_profile.user_type }} but then what? Or how would I add a method to the model like is_type_xxx so that I could use it in the template?

Upvotes: 0

Views: 1456

Answers (3)

Fraser Graham
Fraser Graham

Reputation: 4820

Maybe I don't fully understand the question, but it seems you can just define a function in your model that returns true if the type is what you need, then you can call that function from the template just as you would if you were accessing a variable.

In the model...

user_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
details = generic.GenericForeignKey('user_type', 'object_id')

def IsTypeX():
    return user_type == x

In the template...

{% if user.get_profile.IsTypeX %}
{% endif %}

Upvotes: 2

Peter Rowell
Peter Rowell

Reputation: 17713

Although Ignacio is basically correct, I find that there can be a really tendency to get a lot of unintended DB hits if you're not careful. Since the number of ContentTypes tends to be small and relatively unchanging, I cache a dict of name/id pairs to avoid it. You can use a signal to update your dict on the off chance a new ContentType is created.

You can then auto-create the necessary is_type_xxx() functions/methods as needed. It's a little klunky, but the code isn't very complicated.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799490

user_type is a ForeignKey to a ContentType model, so treat it as you would any relation.

Upvotes: 1

Related Questions