Django if statement doesn't work as expected - python

I have the following in my html file:
{% trans "Result: "%} {{result}}
Which will print out the word SUCCESS on the browser (because thats what the string contains)
But If I do the following:
{% if result == 'SUCCESS' %}
do something
{% else %}
do something else
{% endif %}
I find that the if statement does not work as expected.
Why is this??

The if statement works fine. Your problem must be regarding the string. Maybe it's not a string at all.
Try the ifequal templatetag:
{% ifequal result 'SUCCESS' %}
do something
{% else %}
do something else
{% endifequal %}
You can try different things. If you're assigning result in a view, you can validate it's a string in that very same view:
def my_view(request):
# ... processing ...
result = something()
# Let's make sure it's a string containing 'SUCCESS'
assert type(result) == str
assert result == 'SUCCESS'
You can apply the same logic if it's a context processor.
https://docs.djangoproject.com/en/dev/ref/templates/builtins/?from=olddocs#ifequal

Check this link:
Django String format.
according to django documentation you should use this format:
{% if result|stringformat:"s" == 'SUCCESS' %}
do something
{% else %}
do something else
{% endif %}
or
{% if result|stringformat:"s" in 'SUCCESS' %}
do something
{% else %}
do something else
{% endif %}
or
{% ifequal result|stringformat:"s" 'SUCCESS' %}
do something
{% else %}
do something else
{% endif %}
this problem happen because of your variable type, you should change it to string before compare it to another string.

Related

How to check if Django Queryset returns more than one object?

Basically I have what I'm hoping is a simple issue, I just want to check if the Queryset contains more than one object but I'm not sure how to do it? What I've written (that doesn't work) is below.
{% if game.developer.all > 1 %}
<h1>Developers:</h1>
{% else %}
<h1>Developer:</h1>
{% endif %}
Using count() to check the total objects in the QuerySet:
{% if game.developer.all.count > 1 %}
<h1>Developers:</h1>
{% else %}
<h1>Developer:</h1>
{% endif %}
https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#pluralize
<h1>Developer{{ game.developer.count|pluralize }}:</h1>

How to check if a dict's member is equal to a string in Jinja2

I have a Jinja2 Template that I am serving in flask that looks somthing like this:
{% if current_user.UserType == “Admin” %}
Stuff
{% endif %}
However I am getting an error like this
TemplateSyntaxError: unexpected char u'\u201c' at 860
What is the proper way to check a key's value in Jinja2?
It looks like the problem was the one downshift mentioned with encoding, I was under the impression that it was somthing to do with the jinja2 syntax but,
{% if current_user.UserType == "Admin" %}
Stuff
{% endif %}
works just fine.
Use bracket notation:
{% if current_user["UserType"] == “Admin” %}
Stuff
{% endif %}
Or the get method:
{% if current_user.get("UserType") == “Admin” %}
Stuff
{% endif %}
Also use Google

Flask, get value from checkbox and pass the result to another template

I am using Weasyprint, to display some jinja templates in a Flask Web App.
I have this json.
value=["1","2","3","4"]
I want to pass 'value' to another jinja template in an if statement.
{% if (value|int =["1", "2", "3", "4"]) %}
{% include 'pages/page1.html' %}
{% else %}
{% include 'pages/page2.html' %}
{% endif %}
But this shows the error,
TemplateSyntaxError: expected token ')', got '='
I thought I had to convert json to int in order to make it work.
The Jinja2 int filter will fail on your list as it will be trying to cast it to a single integer value. Therefore it will return 0. Also = is an assignment operator and == is a comparator. Try this to get the intended result:
{% if value|join("|") == "1|2|3|4|5" %}
{% include 'pages/page1.html' %}
{% else %}
{% include 'pages/page2.html' %}
{% endif %}

Django - Template with 'if x in list' not working

I have a Django template that looks something like this:
{% if thing in ['foo', 'bar'] %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
The problem is it comes back empty. If I switch to this:
{% if thing == 'foo' or thing == 'bar' %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
it works fine. Is there some reason you can't use x in list in Django templates?
You can. But you can't use a list literal in templates. Either generate the list in the view, or avoid using if ... in ....
I got it working with the help of this answer. We could use split to generate a list inside the template itself. My final code is as follows (I want to exclude both "user" and "id")
{% with 'user id' as list %}
{% for n, f, v in contract|get_fields %}
{% if n not in list.split %}
<tr>
<td>{{f}}</td>
<td>{{v}}</td>
</tr>
{% endif %}
{% endfor %}
{% endwith %}
Send the list from the context data in the view.
Views.py:
class MyAwesomeView(View):
...
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['list'] = ('foo', 'bar')
...
return context
MyTemplate.html:
{% if thing in list %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
Tested on Django version 3.2.3.
There is a possibility to achieve that also by creating a custom filter:
Python function in your_tags.py:
from django import template
register = template.Library()
#register.filter(name='is_in_list')
def is_in_list(value, given_list):
return True if value in given_list else False
and passing your list to html django template:
{% load your_tags %}
{% if thing|is_in_list:your_list %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
or without passing any list - by creating a string containing your list's values (with a filter you still can't use list literal), e.g.:
{% load your_tags %}
{% if thing|is_in_list:'foo, bar' %}
Some HTML here
{% else %}
Some other HTML
{% endif %}
[TIP] Remember not to insert space after :.

Django: Issues with if condition in templates

I want to print something on the basis of the current language code. For that I did something like this:
{% if request.LANGUAGE_CODE == en %}
<h1>English</h1>
{% endif %}
But this if condition does not compare the current language code. But if I print this {{request.LANGUAGE_CODE}} on the same page then it will print en as language code, but my if condition is not working and I don't know why ??
LANGUAGE_CODE is a string, so you just need to enquote your comparison value like this:
{% if request.LANGUAGE_CODE == 'en' %}
<h1>English</h1>
{% endif %}
check also the ifequal tag
{% ifequal request.LANGUAGE_CODE 'en' %}
...
{% endifequal %}
a bit more: the if and ifequal on strings are case sensitive, so you may want to be sure you're matching the correct case (maybe applying the |lower filter to both arguments)

Categories

Resources