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 %}
Related
{% for index in length %}
{{index}}
<img src={{image_url.index}} width="200" height="250">
{% endfor %}
length contains number list from 0 to 38 i.e. [0,1,2,......38]
The image_url contains the list of image urls that I want show in my webpage. The {{index}} code run properly and show the index number from 0 to 38. But when I try to display image using {{image_url.index}} no image is displayed. Is there an solution for this?
Django does not convert your index to this value for getting the image_url corresponding.
Why do you not loop on image_url ?
{% for url in image_url %}
{{forloop.counter0}}
<img src={{url}} width="200" height="250">
{% endfor %}
Else, you have to create a custom filter (https://docs.djangoproject.com/en/4.1/ref/templates/builtins/):
# templatetags/extras.py
from django import template
register = template.Library()
#register.filter
def get_item(array, key):
return array[key]
# in template
{% load extras %}
{{image_url|get_item:index}}
I want to get m2m data in my template through the views but failing to do so. The thing is that I'm able to show the data of m2m field looping it from template itself but it does slow down the website.
My Team apps Model looks like this:
class Team(models.Model):
title = models.CharField(max_length=255)
team_country = CountryField(max_length=200, blank=True, null=True)
members = models.ManyToManyField(User, related_name='teams')
created_by = models.ForeignKey(User, related_name='created_teams', on_delete=models.CASCADE)
Now in my tournament app I'm trying to get "members" of the team.
My Tournamet Views look like this:
def tournament_page(request, slug):
page = 'tournament_page'
user = request.user
tournament = Tournament.objects.get(slug=slug)
players = tournament.participants.select_related('user')
all_players = Profile.objects.select_related('user')
side_tourneys_ongoing = Tournament.objects.filter(state='Ongoing')[:10]
side_tourneys_upcoming = Tournament.objects.filter(state='Upcoming')[:10]
side_tourneys_completed = Tournament.objects.filter(state='Completed')[:10]
teams = Team.objects.select_related('created_by')
context = {
'page': page,
'tournament': tournament,
'side_tourneys_ongoing': side_tourneys_ongoing,
'side_tourneys_upcoming': side_tourneys_upcoming,
'side_tourneys_completed': side_tourneys_completed,
'teams': teams,
'players':players,
'all_players':all_players
}
Now I'm able to show the teams with their members in the template using for loop inside the template itself as:
Html template
<div class="grid-x">
{% for team in teams %}
{% for player in players %}
{% if team.id == player.active_team_id and team.game == tournament.game %}
<div class="wf-card event-team">
<div> {{team.title}} </div>
<div class="event-team-players">
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
{% endfor %}
</div>
What I want is to use this piece of code
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
in my views since it causes the website to slow down and idk why.
What I tried in my views is:
all_teams = Team.objects.all()
members = all_teams.members.all()
and
members = Team.objects.all().prefetch_related('members')
First one throws an error:
'QuerySet' object has no attribute 'members'
Second one shows lots of blank records
Tried almost everything with search but none of them helped except using the code that I provided directly in the template itself.
Edited based on comments below. You should be able to do this more simply by prefetching team members.
views.py
def tournament_page(request, slug):
page = 'tournament_page'
user = request.user
tournament = Tournament.objects.get(slug=slug)
all_players = Profile.objects.select_related('user')
side_tourneys_ongoing = Tournament.objects.filter(state='Ongoing')[:10]
side_tourneys_upcoming = Tournament.objects.filter(state='Upcoming')[:10]
side_tourneys_completed = Tournament.objects.filter(state='Completed')[:10]
teams = Team.objects.select_related('created_by').prefetch_related('members')
template.html
<div class="grid-x">
{% for team in teams %}
{% if team.game == tournament.game %}
<div class="wf-card event-team">
<div> {{team.title}} </div>
<div class="event-team-players">
{% for member in team.members.all %}
{{ member.username }}
{% endfor %}
</div>
</div>
{% endif %}
{% endfor %}
</div>
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 ?
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 %}
I've created a system for my client to be able to display a product details/specification table on product pages with product tags which works similar to the Supply theme's grouped filter tags eg. a product that has a tag "Brand_Philips" will automatically add a row to the table with the first column being "Brand" and the second "Philips".
I added an input in the theme settings_schema.json so my client should be able to add/remove and reorder the details, and all I have to do now is just loop thru the new setting and check if there is a matching tag and add it to the table, but for some reason when I loop the details within the tags loop everything works fine and when I loop the tags within the details the whole page get's messed up.
Here's my code:
In settings_schema.json:
{
"name": "Sort Product Details",
"settings": [
{
"type": "text",
"label": "Type the product detail tags in a comma-separated list.",
"id": "product_details",
"info": "List items must be identical to the tag prefixes (no underscore), and have no spaces between commas.ie. Brand,Avarage Lifetime,Watts,Volts"
}
]
}
In the product page I wrote this code:
{% assign marker = '_' %}
{% assign productDetails = settings.product_details | split: ',' %}
{% assign found = false %}
{% for tag in product.tags %} <!-- The tags loop -->
{% for detail in productDetails %} <!-- The details loop -->
{% if tag contains marker and tag contains detail %}
{% if found == false %}
{% assign found = true %}
<hr>
<h3>Product Details:</h3>
<table class="table-striped">
{% endif %}
{{ tag | replace: marker, ': </strong></td><td>' | prepend: '<tr><td><strong>' | append: '</td></tr>' }}
{% if found and forloop.last %}</table>{% endif %}
{% endif %}
{% endfor %}
{% endfor %}
Notice that I loop details within the tags loop but when I loop the tags within the details loop my page get's all messed up.
Here's how my page looks normally:
And here's how my page looks when I loop the tags within the details loop:
The reason I want it to loop the tags within the details loop is that I want my client to be able to reorder the details - and it should not display in its alphabetical order - the way the tag loop works.
Thanks in advance!
Martin.
After asking this question on the Shopify forums I got an answer and would like to share it here.
The reason why it all got messed up is that the closing </table> tag was only added at the end of the loop with this code {% if found and forloop.last %}</table>{% endif %} and when rendering only the tags that are included in the details it never reached the last tag.
So here is my fixed code:
{% assign marker = '_' %}
{% assign productDetails = settings.product_details | split: ',' %}
{% assign found = false %}
{% for detail in productDetails %}
{% for tag in product.tags %}
{% if tag contains marker and tag contains detail %}
{% if found == false %}
{% assign found = true %}
<hr>
<h3>Product Details:</h3>
<table class="table-striped">
{% endif %}
{{ tag | replace: marker, ': </strong></td><td>' | prepend: '<tr><td><strong>' | append: '</td></tr>' }}
{% endif %}
{% endfor %}
{% if found and forloop.last %}</table>{% endif %}
{% endfor %}
Note that the tag loop is in the details loop and the closing </table> tag is added in the end of the details loop.