I am using a for loop in an HTML Template, it recognizes the fact that they are there but it does not show them in the page like it should.
my views:
person = []
x = people.objects.filter(deal='q')
for person in x:
print(person.name)
if person.paid_status == True:
person.append(lender)
return render(request, '.html', {'person': person})
my template:
<div>
{% if person %}
There are {{ person|length }} persons.
{% for p in person %}
<p> {{ p.name }} </p>
{% endfor %}
{% else %}
<p> As of now no persons have appeared. </p>
{% endif %}
</div>
in the console it prints the persons name correctly so I am confused why it does not work in the HTML
All I see is that there are 2 persons(which is correct) but then it does not list them.
Thanks in advance.
You are overwriting the variable person inside your loop.
Change the list person to persons and it should work fine.
Your view:
persons = []
x = people.objects.filter(deal='q')
for person in x:
if person.paid_status == True:
persons.append(person)
return render(request, '.html', {'persons': persons})
Your template:
<div>
{% if persons %}
There are {{ persons|length }} persons.
{% for p in persons %}
<p> {{ p.name }} </p>
{% endfor %}
{% else %}
<p> As of now no persons have appeared. </p>
{% endif %}
</div>
Related
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 am creating a to do list. I want to display the tasks if the user has any. If not, then display something else. I kept the design simple.
<h2>Here is the list of tasks! Start working!</h2>
{% if obj in task %}
<ul>
{% for obj in task %}
<li>{{ obj }}</li>
{% endfor %}
</ul>
{% else %}
<p>You dont have anything on this list yet!</p>
{% endif %}
The 'task' is the queryset and currently consists of 2 objects. But none of them are being displayed. Everything was working fine before I tried to apply the presence check. Now it just jumps to that else statement.
views.py:
def task(request):
task = Task.objects.filter(user=request.user)
queryset = task.order_by('-start_date')
context = {
'task': queryset,
}
return render(request, 'task-list.html', context)
Try in this way
<h2>Here is the list of tasks! Start working!</h2>
{% if task %}
<ul>
{% for obj in task %}
<li>{{ obj }}</li>
{% endfor %}
</ul>
{% else %}
<p>You dont have anything on this list yet!</p>
{% endif %}
Its {% if task %} not {% if obj in task %}
Hope this helps you, If anything please let me know
I'm having dict which can be seen here https://jsoneditoronline.org/?id=a570322381fc45919a7a03ebad78cbee
but from what I was reading so far, it's more likely a list of dicts. I am trying to display data from dicts like title, description, authors and categories but template tags are not displaying this what I want, tried with loops but can't access it
Tried loops like this
{% for items in books %}
{% for volumeInfo in items %}
{{ volumeInfo.title }}
{% endfor %}
{% endfor %}
only what works is {{ books.items }} but it's giving me the whole json but I need only few values.
def api(request):
books = {}
if 'books' in request.GET:
books = request.GET['books']
url = 'https://www.googleapis.com/books/v1/volumes?q=%s' % books
response = requests.get(url)
books = response.json()
print(type(books))
with open("data_file.json", "w") as write_file:
json.dump(books, write_file)
return render(request, 'books/api.html', {'books': books})
{% load get_item from template_filters %}
{% block content %}
<h2>Google API</h2>
<form method="get">
<input type="text" name="book">
<button type="submit">search on google books api</button>
</form>
{% if books %}
<p>
{% for items in books %}
{% for volumeInfo in items %}
{{ volumeInfo.title }}
{% endfor %}
{% endfor %}
{{ books.items }}
</p>
{% endif %}
{% endblock %}
You need to follow the structure of the JSON that you have. Summarising, the data looks like this:
{
"items": [
{
"volumeInfo": {
"title": "Hobbit czyli Tam i z powrotem"
}
}
]
}
So, in the template:
{% for item in books.items %}
{{ item.volumeInfo.title }}
{% endfor %}
I am having trouble understanding how I might show a "no posts exist" message for a particular conditional statement with two variables.
In this example, let's say I have a collection of "animals" - on a particular page, I'd like a section that displays "primates that are herbivores":
{% for animal in site.animal %}
{% if animal.species == "primate" and animal.type == "herbivore" %}
{{ animal.content }}
{% endif %}
{% endfor %}
What I'd like to do is something like this (pseudocode):
{% if POSTS_EXIST_FOR_THIS_COMBO: (animal.species == "primate" and animal.type == "herbivore") %}
{% for animal in site.animal %}
{% if animal.species == "primate" and animal.type == "herbivore" %}
{{ animal.content }}
{% endif %}
{% endfor %}
{% else %}
There are no posts for this category.
{% endif %}
Note: This differs from examples like this, because I have two parameters to check. Can someone offer a suggestion about the syntax?
I think you can do the following where you at first filter all by species=primate from site.animal and then filter by type=herbivore from that pool and then check if the result exists.
{% assign animals = site.animal | where:"species","primate" | where:"type","herbivore" %}
{% if animals %}
{% for animal in animals %}
{{ animal.content }}
{% endfor %}
{% endif %}
Hope this helps.
As the title says, here's what I've got:
form = F(obj = myobject)
myfieldlist= FieldList(FormField(form))
{% for subfield in form.myfieldlist %}
{{ subfield.field }}
{{ subfield.label }}
{% endfor %}
This outputs nothing, any ideas? Also, not entirely sure if FormField is required.
Thanks
FormField takes a class not an instance:
class GuestForm(Form):
email = TextField()
vip = BooleanField()
class VenueForm(Form):
name = TextField()
guests = FieldList(FormField(GuestForm))
Then in your controller:
form = VenueForm(obj=myobject)
render("template-name.html", form=form)
In your template you will need to iterate over the FieldList field as if it was its own form:
{% for guest_form in form.guests %}
<ul>
{% for subfield in guest_form %}
<li>{{ subfield.label }} {{ subfield }}</li>
{% endfor %}
</ul>
{% endfor %}