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 %}
If statement in PythonAn if statement starts with if keyword which should always be written in lowercase followed by an expression. If the expression returns a True value then the statement below the if statement will get executed and if it returns False then the interpreter will skip over this part.
{% %} and {{ }} are part of Django templating language. They are used to pass the variables from views to template. {% %} is basically used when you have an expression and are called tags while {{ }} is used to simply access the variable.
Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .
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
How about this one:
{% is_designer user.id as is_user_designer %}
{{ is_user_designer|yesno:"Yes," }}
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