Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template Tag Conditional

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 %}

like image 461
JREAM Avatar asked Apr 29 '13 18:04

JREAM


People also ask

How do you write if condition in Django?

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.

What does {% %} mean in Django?

{% %} 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.

What characters surround the template tag in Django?

Answer and Explanation: Answer: (b) {% . In Django the template tag is surrounding by {% .


2 Answers

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

like image 61
Ngenator Avatar answered Sep 19 '22 05:09

Ngenator


How about this one:

{% is_designer user.id as is_user_designer %}
{{ is_user_designer|yesno:"Yes," }}
like image 40
mehmet Avatar answered Sep 19 '22 05:09

mehmet