Reputation: 5931
How make a a conditional statement out of a Django Template Tag?
from django import template
from django.contrib.auth.models import User, Group
register = template.Library()
@register.simple_tag
def is_designer(user_id):
try:
group = Group.objects.get(
name = "Designer",
user = user_id
)
return True
except Group.DoesNotExist:
return False
This appears True or False in my template which is correct:
{% is_designer user.id %}
However these gives me an error "Unused 'user.id' at end of if expression.":
{% if is_designer user.id == True %} Yes {% endif %}
{% if is_designer user.id %} Yes {% endif %}
Upvotes: 5
Views: 13277
Reputation: 11259
If you made that into an assignment tag, you could do something like
{% is_designer user.id as is_user_designer %}
{% if is_user_designer == True %} Yes {% endif %}
{% if is_user_designer %} Yes {% endif %}
Note: As of Django 1.9, assignment tags are deprecated and simple tags can store values now. See the deprecation notice in the 1.9 docs https://docs.djangoproject.com/en/1.9/howto/custom-template-tags/#assignment-tags
Upvotes: 14
Reputation: 8144
How about this one:
{% is_designer user.id as is_user_designer %}
{{ is_user_designer|yesno:"Yes," }}
Upvotes: 1