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

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

Related

Assign a value to a variable already declared in the template in django?

I googled but unable to find the solution. Where I went thought some answers like This answer
Some official docs which I went through Trans Tag Built-In Tags
Template View
{% load custom_tags %}
{% for each in content %}
{% with tempID='' %} # It is initially empty string
{% if each.contentID != tempID %}
{% tempID = each.contentID %} # Want to assign new value to tempID
....
..
{% endif %}
{% endwith %}
{% endfor %}
Is there any method to assign with tag variable. I tried custom_tags filters also. Not worked.
Is there any method to assign with tag variable?
Yes, you can simply use the {% with tempID= each.contentID %} which in this case will assign a new value to the variable.
Alternative
Variables in templates are merely used to display values and are not often used in a way in which calculation or reassignment is performed. In such cases though you can solve it by using a Django custom filter. See the example below.
.py file - Assign a value to a variable
#register.filter(name='update_variable')
def update_variable(value):
data = value
return data
.HTML file
{% with "true" as data %}
{% if data == "true" %}
//do somethings
{{update_variable|value_that_you_want}}
{% else %}
//do somethings
{% endif %}
{% endwith %}
Note that when you are using Django filters the variable instance resides in Python and not directly in the Template.

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

'for' statements should use the format 'for x in y': while iterating over value retrieved from dictionary using django template

I have a context dictionary entry objectives that maps objective query objects to a list of tests that belong to that objective. Example code:
objectives = Objective.objects.filter(requirement=requirement)
context_dict["requirements"][requirement] = objectives
for objective in objectives:
tests = Test.objects.filter(objective=objective)
context_dict["objectives"][objective] = tests
In my django html template, I iterate over objectives and display them. I then want to iterate over the tests that belong to these objectives. When I do this:
{% for test in {{ objectives|get_item:objective }} %}
I get a TemplateSyntaxError: 'for' statements should use the format 'for x in y':
In the application/templatetags directory, I have:
from django.template.defaulttags import register
...
#register.filter
def get_item(dictionary, key):
return dictionary.get(key)
If instead I make {{ objectives|get_item:objective }} a JS variable, I see that it does indeed produce a list, which I should be able to iterate over. Of course, I can't mix JS variables and the django template tags, so this is only for debugging:
var tests = {{ objectives|get_item:objective }}
var tests = [<Test: AT399_8_1>, <Test: AT399_8_2>, <Test: AT399_8_3>, <Test: AT399_8_4>, <Test: AT399_8_5> '...(remaining elements truncated)...']
How do I iterate over this list in the django template tag?
You cannot user {{...}} inside the {%...%}
What you can try is changing your filter to an assignment tag and using that value in the loop
#register.assignment_tag
def get_item(dictionary, key):
return dictionary.get(key)
And then in your template use it as
{% get_item objectives objective as tests %}
{% for test in test %}
....
{% endfor %}
Instead of all this if your models are proper with foreign keys I would do something like
{% for objective in requirement.objective_set.all %}
{% for test in objective.test_set.all %}
....
{% endfor %}
{% endfor %}
In my context I would pass only the requirement
You already have an answer, but note that dropping the {{ }} tags and keeping everything else the same would have worked fine.
{% for test in objectives|get_item:objective %}
**This is Right Answer for Using Django if else and for loop **
Note :- We Have to Put Key in " " string (Double quotes) some time produce an error so That is good way bcz i faced that problem whwn i Learned
{% if 'numbers'|length > 0 %}
{% for i in numbers %}
{% if i > 20 %}
{{i}}
{% endif %}
{% endfor %}
{% else %}
Empty
{% endif %}

Django if statement doesn't work as expected

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.

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 :.

Categories

Resources