django foorloop counter restarts in a new page - python

currently I'm writing a simple todolist with django. I have a view and html file for showing the list of items, and I want a number for each task in the table starting from 1. I'm using {% footloop.counter %} for that in my template.
Everything was ok until I wrote the paginator. when you choose to go to the next page, the counter starts from 1 again ,therefor the numbers in the table in each page start from one too. but I want the numbers to be continued in order until the last page. Is there any template tags or code snippets for that?
Thanks in advance.
here are the codes involved:
**list.html:**
{% for task in tasks %}
<tbody>
<tr>
<th scope="row" class="col-md-1">{{ forloop.counter }}</th>
<td class="col-md-2">{{ task.title }}</td>
<td class="col-md-3">{{ task.description|truncatewords:10 }}</td>
<td class="col-md-2">{{ task.time|date:"H:i" }} - {{ task.time|date:"D d M , Y" }}</td>
</tr>
</tbody>
{% endfor %}
<!--Pagination-->
{% if is_paginated %}
<div class="container p-4">
<div class="pagination justify-content-center">
<span class="step-links">
{% if page_obj.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ page_obj.number }} of {{page_obj.paginator.num_pages }}
</span>
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
{% endif %}

You can try to build your own template tag and use it on the template like below :-
#register.filter
def adjust_for_counter(value, page):
value, page = int(value), int(page)
counter_value = value + ((page - 1) * settings.RESULTS_PER_PAGE)
return counter_value
and call it like below in the html :-
{{ forloop.counter|adjust_for_pagination:page }}
For more details you can refer to below link :-
https://djangosnippets.org/snippets/1391/

Related

For loop returning iterations of same result from OMDB API

I have been scouring the internet for the answer to this and I am at the point where I feel like I am probably missing something glaringly in my face.
I am attempting to request search results from the omdb api (https://www.omdbapi.com/). I have create countless iterations of the screenshots below, but here is where I am at right now with my code.
Essentially, I am able to see the movie title and year for only the first search result, and I cannot figure out how to loop through each result and display on my webpage. Any help is appreciated.
Code below:
(python code)[https://i.stack.imgur.com/6xVsL.png]
(html)[https://i.stack.imgur.com/crWk7.png]
(terminal)[https://i.stack.imgur.com/wq65p.jpg]
(webpage result)[https://i.stack.imgur.com/sLNdF.png]
Copy/Pasted Code:
app.py:
#app.route('/movies/search_results', methods=['GET'])
def show_search_results():
"""Logic for sending an API request and displaying the JSON response as an HTML. Expects a GET request."""
movies = []
s = request.args.get("search")
results = requests.get(f"{API_BASE_URL}search/movies/",params={"s": s}).json()
results = results['Search']
for movie in results:
movies.append(movie)
return render_template('movies/search_results.html', movies=movies)
#app.route('/movies/detail')
def show_movie_details():
"""For displaying information about the individual movie. Not a list. GET request only."""
movie = requests.get(f'{API_BASE_URL}', params={"i":id})
print(movie)
return render_template('movies/detail.html', movie=movie)
search_results.html:
{% block title %} {% endblock %}
{% block nav1 %} active {% endblock %}
{% block content %}
<div class="container-fluid" id="movie-list">
<div class="row row-cols-2 justify-content-center mt-2" style="--bs-gutter-x:0; ">
<p> Search Results for "{{s}}"</p>
<table>
<thead>
<tr>
<th>IMDB ID</th>
<th>Movie Title</th>
<th>Year Released</th>
</tr>
</thead>
<tbody>
{% for movie in movies %}
<tr>
<td>
<a href="/movies/detail" id="id">
{{ movie['imdbID'] }}
</a>
</td>
<td>
{{ movie['Title'] }}
</td>
<td>
{{ movie['Year'] }}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
{% endblock %}
{% block footer %} {% endblock %}
{% extends 'base.html' %}
{% block content %}
<div class="card mb-3">
<div class="card-body">
<h5 class="card-title">Title: {{ movie['Title'] }}</h5>
<p>
<span class="text-info">Description: </span>
</p>
<div><h5 class="card-title text-success">Playlists with this movie:</h5></div>
<p class="card-text"></p>
</div>
</div>
{% endblock %}
I did try creating an empty variable, and then assigning the results of my for loop to that variable as an iterable, but I ran into the same problem there too.
Try not using the 'page' key in the params dict you are passing in the api request, then you should get all the results.
Also as mentioned in #Barmar comment you are returning your results inside the loop, you should move the return statement one tab to the left.

Send list of lists data and put it to table in html

I get data from the pandas(DataFrame), which is in list of lists, like [['jay', 'M', 'CS'],[],[]] and so on . How can i put this data in table. I directly push the list-data in html file. first loop works fine, but it didn't pass in second loop, How can I do that? I am new to html.
{% for post in post_data %}
<tr>
{% for value in post %}
<td>
{{value}}
</td>
{% endfor %}
</tr>
{% endfor %}
i pass 'tables': [df.to_html(classes='data', header="true")], data display in raw html.
<div class="card card-stats">
<div class="card-body ">
<div class="card-header ">
<!--div class="progress-container progress-info"-->
<!--<h6 class="card -title" style="color:#FFFFFF; background-color:#008B8B;" align="center">DataFiles</h6>-->
<table id="TripGrid" class="datafiletable" cellspacing="0" width="100%">
<thead style="background-color: #6699FF">
{% for header in post_header %}
<th>{{header}}</th>
{% endfor %}
</thead>
<tbody>
{% for table in tables %}
{{table}}
{% endfor %}
</tbody>
</table><br>
</div>
</div>
</div>

Django: how can I display 1 field item as a header w/ remaining field items as the value?

I have a table displayed inside a collapsible, accordion style card component that contains three Fielditems (one per<td>). Using a forloop.counter, I am trying display each obj.frequency as the collapsible-header with all of the associated obj.product and obj.price items displaying within the collapsible-body.
I recognize the current layout needs to be DRY-er by only using the object.rate_set.all loop once. I left the two obj forloops since this is the only way I can get the data within the collapsible-body section of the card, even though the data is not separated correctly.
Question:
How can I display the data associated with frequency inside a card body with the frequency obj output as the header?
In addition to my template, a screenshot of my browser is included below for clarification if needed
My Template:
<div class="card">
<div class="card-body">
<ul class="collapsible popout">
{% for obj in object.rate_set.all %}
<!-- -------------------------------------------------
displays each `frequency` obj in its own accordion card
as the header. output: 1x, 3x, 6x, 12x, 24x..
------------------------------------------------- -->
{% if forloop.counter|divisibleby:3 %}
<li>
<div class="collapsible-header“>{{ obj.frequency }}</div>
<div class ="collapsible-body">
{% endif %}
{% endfor %}
<div class="table-responsive card-text">
<table>
<thead>
<tr>
<th>Product</th>
<th>Rate</th>
</tr>
</thead>
<tbody>
<!-- -----------------------------------
displays all of the obj's in the last
accordion card (24x)
------------------------------------- -->
{% for obj in object.rate_set.all %}
<tr>
<td> {{ obj.product }} </a>
<td>${{ obj.price }}</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div> <!–- end of ‘collapsible-body' -->
</li>
</ul>
</div>
</div>
Based on #DisneylandSC's response- below is the updated working template:
<div class="card">
<div class="card-body">
{% regroup object.rate_set.order_by by frequency as frequency_list %}
<ul class="collapsible popout">
{% for frequency in frequency_list %}
<li>
<div class="collapsible-header">
<i class="material-icons">view_day</i>{{ frequency.grouper }} Frequency Rate
</div>
<div class="collapsible-body">
<div class="table-responsive card-text">
<table class="table highlight">
<thead>
<tr>
<th>Product</th>
<th>Price</th>
</tr>
</thead>
<tbody>
{% for item in frequency.list %}
<tr>
<td>
<a class="nav-link" href="#">
{{ item.product }}
</a>
</td>
<td>${{ item.price }}</td>
</tr>
{% endfor %}
</table>
</div>
</div>
</li>
{% endfor %}
</ul>
</div>
</div>

Django Break Loop in template

Im currently displaying a table with values, and in case those values doesn't exist im displaying a button to introduce such values.
The problem is that i need a break in the for loop but Django doesn't support break in templates.
The current state is this:
And the html for the table is the following:
<table style="width:100%">
<tr>
<th>Num de aluno</th>
{% for quest in questionlist
<th> {{quest.question_id.q_discription}} </th>
{% endfor %}
</tr>
{% for st in students %}
<tr>
<td> {{st.student_number}} </td>
{% for qt in questionlist %}
<td>
{%for tst in studentexamitems %}
{% if qt == tst.qitem_id and st == tst.student_id %}
{{tst.qscore}}
{% endif %}
{% endfor %}
<a href="{% url 'newTableEntry' qt.id st.id %}">
<button type="button" class="btn btn-success btn-xs">
<span class="glyphicon glyphicon-plus"></span> Grade
</button>
</a>
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
So the question is how do i remove the button in case of a existing grade, and keep the button in case of not existing?
As stated on the comments, there is no break in Django template system.
You can still solve this using if ... else.
If a grade is available, show the grade; if grade is not available, show the button.
{% for tst in studentexamitems %}
{% if qt == tst.qitem_id and st == tst.student_id %}
{{tst.qscore}}
{% else %}
<a href="{% url 'newTableEntry' qt.id st.id %}">
<button type="button" class="btn btn-success btn-xs">
<span class="glyphicon glyphicon-plus"></span> Grade
</button>
</a>
{% endif %}
{% endfor %}

Form fields not displayed in django html

I have written a code to make form , and i have no guess why the fields are not displayed here are my codes.
I want to get a request from the index.html page and using that request, I ran a query to display the results of the query on the same page.
views.py
def search123(request):
searc=search1()
if request.method=="POST":
searc=search1(request.POST or None)
if searc.is_valid():
if 'd_box' in request.POST:
item_map=item.objects.raw('SELECT * FROM `item` WHERE `category_id`=%s', [request.POST['d_box']])
lis=[]
for e in (item_map):
lis.append(e.id)
price_map=item_done.objects.filter(item_id__in=lis).order_by('item_id')
return render_to_response('index.html',{'posts':price_map},RequestContext(request))
return render_to_response('index.html',{'posts':searc},RequestContext(request))
index.html
<html>
<head>
</head>
<body>
<form method='POST' action=''>{% csrf_token %}
<h4> SEARCH </h4>
{{searc.as_table}}
<input type='submit' name="button7" value="button7">
</form>
{% regroup posts by item_id as post_list %}
<table border="4" style="width:1050px;border-collapse: collapse" >
<thead>
<tr>
<th>Item Codes</th>
<th>Name</th>
<th>MRP</th>
<th>Site price</th>
<th>Website</th>
</tr>
</thead>
<tbody>
{% for country in post_list %}
<tr>
<td>{{ country.grouper }}</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.name}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.mrp}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.site_price}}</div>
{% endfor %}
</td>
<td>
{% for item in country.list %}
<div style="margin: 5px 5px">{{item.crawl_id}}</div>
{% endfor %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</html>
forms.py
class search1(forms.ModelForm):
class Meta:
model=search
exclude=[]
i think you must import search model in forms.py an also in your template you write the form name wrong ! you write {{searc.as_table}} it must be {{search.as_table}}

Categories