validation in django templates - html

I have a django template in which I wanna show the user only if it's name is emp for which I am using the following code:
HTML
{% if warehouse.warehouse.owner == emp %}
<td class="align-middle">{{ warehouse.warehouse.owner }}</td>
{% endif %}
It's not working but when I use this without the if condition it shows emp in the template. How do I equate both of them in the template ?

Related

Using if statement in django template to detect a NULL

My web application stores dances and the YouTube link to that dance. The table shows the dance name and a link to the video which is passed to a new page to show the embedded video. This all works fine but some dances do not have a video and the return from the database for video_id is NULL.as below
http://localhost:8000/video_test/HjC9DidEwPc,%20Big%20Blue%20Tree --- with video
or
http://localhost:8000/video_test/NULL,%20Baby%20Kate ---- with no video
I want include a test for the null in the template which tabulates the dances so that the link does not appear if no video
tabulated output is the word video is a link to video_test
Column A
Column B
The dance name
Video
The dance name
Video
I have tried using {% if i.video == NULL %} is NULL, is None, but none work.I have looked at various other questions which seem to suggest that one of the above should work. I either get an unable to parse error or the if statement has no effect.
.
Model
class Dances(models.Model):
name = models.CharField('name', max_length=120)
video_id = models.CharField('video_id', max_length=50)
level = models.CharField('level', max_length=3)
def __str__(self):
return str(self.name)
view
def video_test(request, id, name):
vid_id= id
d_name = name
return render(request, 'alineapp/video_test.html',{'vid_id':vid_id, 'd_name':d_name})
Template
<!-- Table for Beginner dances -->
<table border="1" cellspacing="2" cellpadding="2">
{% for i in beg_list %}
<tr>
<td>{{ i.name }}</td>
{% If i.video !== NULL %}
<td>Video</td>
{% else %}
<td> None </td>
{% endif %}
</tr>
{% endfor %}
Did you try not none?
{% if i.video is not none %}
<td>Video</td>
{% else %}
<td> None </td>
{% endif %}

How to use the if statement in jinja2 template

I want to check if a condition in the linked database is true and then execute some code but I am getting error such as
jinja2.exceptions.TemplateSyntaxError: expected token ':', got '}'
{% for prod in prod %}
{% if {{prod.sh}} is 1 %}
<pre>Lines to come if true</pre>
{% endif %}
{% endfor %}
The extensive Jinja2 documentation can be found at https://jinja.palletsprojects.com/en/2.11.x/templates/
About your code - I spot two problems.
You should not use for prod in prod - rather, but something like for product in products, ie name them differently.
You do not have to put angle brackets around prod.sh. You would do this only when the variable is referenced directly within the HTML code.
So a working code could look like:
{% for prod in prod %}
{% if prod.sh == 1 %}
<pre>Lines to come if true</pre>
{% endif %}
{% endfor %}

How to add if function in django html template

I want to add an if function in an html template of my django project.
If the variables datas is null, it will show the text "The results is null", if the variables datas is not empty, it will show the table for the data in datas.
Here's what I write, but it raises the error
Invalid block tag on line 13: 'if(isEmpty($('#datas')))', expected 'endblock'.
Did you forget to register or load this tag?
How could I deal with it?
{% if(isEmpty($('#datas'))) %}
<h3>The results is null.</h3>
{% else %}
<table style="table-layout:fixed;">
<tr>...</tr>
<tr>
{% for i in datas %}
<td>{{ i.1 }}</td>
</tr>
{% endfor %}
</table>
{% endif %}
I think you can use empty tag. Use it like this:
<table style="table-layout:fixed;">
<tr>...</tr>
<tr>
{% for i in datas %}
<td>{{ i.1 }}</td>
</tr>
{% empty %}
<h3>The results is null.</h3>
{% endfor %}
But, if you want to check if datas is empty beforehand, then I think its best to do it in views. You can try like this:
def some_view(request):
context = {}
datas = Data.objects.all()
if datas.exists():
context['data_exists'] = True
context['datas'] = datas
return render(request, 'template.html', context)
and use it template:
{% if not data_exists %}
<h3>The results is null.</h3>
{% else %}
....
You can directly use if condition
if you are sending datas from a view
view
def index(request):
datas = None
context = {"datas":datas}
return render(request, "index.html", context)
template
{% if datas %}
<!-- your table -->
{% else %}
<h3>The results is null</h3>
{% endif %}

Flask - Making HTML table of hyperlinks via nested for-loops?

I'm designing a Flask application that works with a MySQL database.
I have this Flask code below:
#app.route("/test")
def test():
cursor.execute("SELECT * from testtable;")
data = cursor.fetchall()
return render_template('test.html', data = data)
I wish to make an HTML table from this data, and I want the first column of this table to be hyper-linked. My current test.html is shown below:
<table border="1" cellpadding="5" cellspacing="5">
{% for row in data %}
<tr>
{% for d in row %}
<td>{{ d }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
This HTML makes a hyper-link out of every cell in every column of the table. Is there a way to make only the cells in the first column be hyper-linked, and make all other cells just show {{ d }}?
The default template engine in Flask is jinja2.
In jinja2 you can check the loop index, which means that you could do something like the following.
{% for d in row %}
{% if loop.index == 1 %} # You can also use loop.index0 for 0-based indexing
<td>{{ d }}</td>
{% else %}
<td>{{ d }}</td>
{% endif %}
{% endfor %}
You can also skip the first element in the row list by using the following syntax:
{% for d in row[1:] %}
In your table, put for for loop outside the tr element.
<table border="1" cellpadding="5" cellspacing="5">
{% for row in data %}
<tr>
<td>{{ row.d }}</td>
{% endfor %}
</tr>
</table>

how to number t-rows ,when table generated using nested forloop in django templates

This part is from views.py
results=[(A,[stuObj1,stuObj2,stuObj3]),(B,[stuObj4,stuObj5,stuObj6]),(C,[stuObj7,stuObj8])]
for tup in results:
total = tot+len(tup[1])
render_to_response(url,{'results':res , 'total':str(tot),})
this is template code:
<th class="name">Name</th>
<th class="id">Student ID</th>
<th class="grade">Grade</th>
{% for tup in results %}
{% for student in tup|last %}
{% with forloop.parentloop.counter as parentloopid %}
{% with forloop.counter as childloopid %}
<tbody class="results-body">
<tr>
<td>{{student.fname|lower|capfirst}} {{student.lname|lower|capfirst}}</td>
<td>{{student.id}}</td>
<td>{{tup|first}}</td>
</tr>
{% endfor %}
{% endfor %}
Now the problems am having are
numbering the rows. Here my problem is am not sure if i can do things like total=total-1 in the templates to get the
numbered rows like <td>{{total}}</td>
applying css to tr:even or odd.
Whats happening in this case is everytime the loop is running the odd/even ordering is lost.
these seems related problems. Any ideas would be great :)
For numbering the rows you can use the forloop.counter
Here you can see an example how to use it.
To switch between even and odd you can use the cycle template tag
{% for project in object_list %}
<tr class="{% cycle odd,even %}"> ... </tr>
{% endfor %}
answer for my question:
Numbering would be a bit time taking. one option is to design custom filters or other way is to modify views and use simple forloop.counter to add, count and forloop.counter. Let me give an example: for the above cases, results are sorted dictionaries with grades and students,something like this ((A:a,b,c,d,e), (B:f,g,h,i), (C:j,k,l,m,n)). In the view add one more dictionary to each tuple with the student count of previous tuple.
temp_count = 0
for tup in results:
tup[1].append({'count':temp_count})
temp_count = temp_count + len(tup[1])-1
-1 is because we don't want to avoid dictionary counted
Inside the template
{% with tup|last|last as cnt %}
{% with forloop.counter as rnum %}
{% with rnum|add:cnt.count as rownum %}
<td>{{rownum}}</td>
rest of code goes here
{% endwith %}
{%endwith%}
{% endwith %}
using {% cycle %} won't be that helpful when using nested loops,
<tr class="{% if rownum|divisibleby:2 %}"even"{% else %}"odd"{% endif %}">
follow this clean way to color.