Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing Django model choices in templates

Say I have a model like:

from django.db import models

USER_TYPE_CHOICES = (
    (1, 'Free'),
    (2, 'Paid'),
)

class Account(models.Model):
    name = models.CharField(max_length=20)
    user_type = models.IntegerField(default=1, choices=TYPE_CHOICES)

and in a template I want to test the user_type to show a special section if the user is of type 'Paid'.

I'd like to do something similar to a C #define or constant to test user_type. So my template code would look like:

{% ifequal user_type PAID_ACCOUNT %}

instead of using a magic number like:

{% ifequal user_type 2 %}

What is the most elegant way to do this in Django? Should I just define a custom context processor with FREE_ACCOUNT and PAID_ACCOUNT in it? Perhaps a template tag?

Thank you!

like image 494
Andrew C Avatar asked Jan 10 '10 00:01

Andrew C


1 Answers

Personally what I would do is add an is_paid(self) method to your Account model which can then be called directly from the template. The added benefit is that this has utility in other parts of your application.

It also gives you the power to do extra processing in the function e.g. a staff member (is_staff) might have their user type automatically set to paid.

like image 155
Aaron Vernon Avatar answered Sep 18 '22 12:09

Aaron Vernon