Issue
I want to create pagination in Django for order list. It seems everything is coded correctly but for some reason when i get to webpage, instead of links to other pages it shows 'Page of . '
Apologies for formatting of this post as it's my first time posting a question and note that there are 7 objects of order, therefore there should be a page.
My code looks like this:
models.py
class Order(models.Model):
date = models.DateField('Date', null=True, blank=True)
car = models.ForeignKey(Car, on_delete=models.SET_NULL, null=True)
ORDER_STATUS = (
('p', 'Processing'),
('o', 'Ordered'),
('s', 'In service'),
('c', 'Completed'),
('t', 'Taken back by customer')
)
status = models.CharField(max_length=1, choices=ORDER_STATUS,
blank=True, default='p')
@property
def order_total_price(self):
order_rows = self.order_row.all()
total_price = sum(row.total_price for row in order_rows)
return round(total_price)
@property
def order_rows(self):
return ', '.join(str(el) for el in self.order_row.all())
def __str__(self):
return f'{self.car}'
views.py
class OrderListView(generic.ListView):
model = Order
context_object_name = "orders"
template_name = "orders.html"
paginate_by = 5
urls.py
from django.urls import path, include
from . import views
urlpatterns = [
path('index/', views.index, name="index"),
path('cars/', views.cars, name='cars'),
path('car/<int:pk>/', views.car_detail, name='car_detail'),
path('orders/', views.OrderListView.as_view(), name='orders'),
path('order/<int:order_id>/', views.order_detail, name='order_detail'),
path('search/', views.search_results, name='search_results'),
path('', views.index, name='index'),
]
and orders.html
{% extends 'base.html' %}
{% block header %}Orders{% endblock %}
{% block content %}
<div class="pagination">
<span class="step-links">
{% if orders.has_previous %}
<a href="?page=1">« First</a>
<a href="?page={{ orders.previous_page_number }}">Previous</a>
{% endif %}
<span class="current">
Page {{ orders.number }} of {{ orders.paginator.num_pages }}.
</span>
{% if orders.has_next %}
<a href="?page={{ orders.next_page_number }}">Next</a>
<a href="?page={{ orders.paginator.num_pages }}">Last »</a>
{% endif %}
</span>
</div>
<h2>List of Orders</h2>
<ul>
{% for order in orders %}
<li>
<a href="{% url 'order_detail' order.id %}">
{{ order.car.client }} - {{ order.car.car_model.brand }}
{{ order.car.car_model.model }} {{ order.car.license_plate }}<br>
</a>
</li>
<br>
{% endfor %}
</ul>
{% endblock %}
Solution
The Django doc on that class states that the context is populated with paginator and page_obj. So you would want to refer to these iso the orders (which is basically the QuerySet for the model).
Based on your example:
- use
page_obj.has_previous
isoorders.has_previous
- use
page_obj.previous_page_number
isoorders.previous_page_number
And so on...
Answered By - gagamil
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.