Solution 1 :

In your HTML, set randomgen to another variable:

{% randomgen as rgen %}

Then use the newly set variable for your conditional:

{% if rgen == 2 %}

Honestly, I was surprised your code didn’t work as your usage makes sense intuitively. Knowing that it doesn’t work though, my guess is the template is comparing a function with an integer which is always going to return False. Good question!

Problem :

I have tried the if condition based on the value defined in the django template

{% if randomgen == 2 %}
<p style="float:right;text-align: center;padding:5px 5px;"><b>{% randomgen %}1</p>
{% else %}
<p style="float:right;text-align: center;padding:5px 5px;"><b>{% randomgen %} 2</p>
{% endif %}

the randomgen is defined to pick in random between 1 and 2 and the value is being displayed correctly in

tag but irrespective of the value it always going to else condition

register = template.Library()

@register.tag(name="randomgen")
def randomgen(parser, token):
    items = []
    bits =  token.split_contents()
    for item in bits:
        items.append(item)
    return RandomgenNode(items[1:])

    def render(self, context):
        arg1 = 0
        arg2 = 10
        if "float" in self.items:
            result = random.randint(1,20)
        elif not self.items:
            result = random.randint(1,20)
        else:
            result = random.randint(1,2)
        return result

Comments

Comment posted by Willem Van Onsem

What is

Comment posted by mh-firouzjah

first make sure the value in

Comment posted by Bibin M

register = template.Library() @register.tag(name=”randomgen”) def randomgen(parser, token): items = [] bits = token.split_contents() for item in bits: items.append(item) return RandomgenNode(items[1:]) def render(self, context): arg1 = 0 arg2 = 10 if “float” in self.items: result = random.randint(1,20) elif not self.items: result = random.randint(1,20) else: result = random.randint(1,2) return result

Comment posted by simmer

Hey Bibin, it’ll be more helpful if you can edit your original question to add the code of

Comment posted by Bibin M

Sure , Have done that .. But basically the issue is more to do with the html reference of the tag . Although the values generated are coming correctky only the if condition is not working correctly

Comment posted by Bibin M

Tried but same . No luck .. Still its always going to the else condition

Comment posted by Zenon Anderson

What version of Django are you using? Also, is there a reason you are using “@register.tag” instead of “@register.simple_tag”?

Comment posted by Bibin M

Django==2.2.5 and have tried simple_tag as well but dint work

Comment posted by Bibin M

Actually it worked . Checked again and it worked .. Thanks a lot Zenon

Comment posted by Zenon Anderson

Awesome! Did you keep your code as is and just change tag to simple_tag?

By