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!
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With