I wanted pagination for all the courses available and that was easy to achieve. But now I'm stuck because I wanted pagination for faculties also, which will show specific courses of the accessed faculty. I have 4 models: faculties, departments, studies, and courses. The pagination will show for faculties as well, but the problem is that if I try to go to the second page, it will redirect me to the second page of all courses list. Or, if I change page on all courses and then try to access a faculty, no course will show at all in the faculty.
def index(request):
course_list = Course.objects.all()
page = request.GET.get('page', 1)
paginator = Paginator(course_list, 1)
try:
courses = paginator.page(page)
except PageNotAnInteger:
courses = paginator.page(1)
except EmptyPage:
courses = paginator.page(paginator.num_pages)
faculty_list = Faculty.objects.all()
page = request.GET.get('page2', 1)
paginator = Paginator(faculty_list, 1)
try:
faculties = paginator.page(page)
except PageNotAnInteger:
faculties = paginator.page(1)
except EmptyPage:
faculties = paginator.page(paginator.num_pages)
context = {'courses': courses,
'faculties': faculties,
'departments': Department.objects.all(),
'studies': StudyProgramme.objects.all(),
'teachers': Teacher.objects.all()
}
return render(request, 'courses/index.html', context)
<div id="crs">
<h3>All courses</h3>
<ul>
{% for course in courses %}
<li><a href={{ course.slug }}>{{ course.name }}</a></li>
{% endfor %}
</ul>
<div class="pagination">
<span class="step-links">
{% if courses.has_previous %}
« first
{{ courses.previous_page_number }}
{% endif %}
<span class="current">
Page {{ courses.number }} of {{ courses.paginator.num_pages }}
</span>
{% if courses.has_next %}
{{ courses.next_page_number }}
last »
{% endif %}
</span>
</div>
</div>
{% for faculty in faculties %}
<div id="fac_{{ faculty.pk }}_tab" style="display:none;">
<h3> {{ faculty.name }} Courses</h3>
<ul>
{% for department in faculty.department_set.all %}
{% for study in studies %}
{% if study.department == department %}
{% for course in courses %}
{% if course.study_programme == study %}
<li>
<a class="first" href={{ course.slug }}>{{ course.name }}</a>
</li>
{% endif %}
{% endfor %}
{% endif %}
{% endfor %}
{% endfor %}
</ul>
<div class="pagination">
<span class="step-links">
{% if faculties.has_previous %}
« first
{{ faculties.previous_page_number }}
{% endif %}
<span class="current">
Page {{ faculties.number }} of {{ faculties.paginator.num_pages }}
</span>
{% if faculties.has_next %}
{{ faculties.next_page_number }}
last »
{% endif %}
</span>
</div>
</div>
{% endfor %}
It's not a Django problem that your view is most certainly handle one pagination parameter page which will direct to courses, so if you changed the get parameter for each of your model pagination it will work.
ex:
## views.py
page = request.GET.get('page')
## yourtemplate.html
yourtext
localhost:8000/MYVIEW/?page=2 # Goes to courses
## views.py
page = request.GET.get('faculties')
## yourtemplate.html
yourtext
##
localhost:8000/MYVIEW/?faculties=2 # Goes to faculties
etc..
edited:
{% for faculty in faculties %} change it to {% for faculty in faculties2 %} and remove faculties from your context, cuz you are repeating yourself as faculties2 and faculties hold the same queryset .
paginator = Paginator(course_list, 1)
paginator = Paginator(faculty_list, 1)
Changing your second instance name to paginator_two would solve your problem
Related
The paginator in django correctly calculates the number of pages, but does not break the models into pages and everything is displayed on 1 page, please tell me what to do with this
This is my views.py,where is a paginator:
from django.shortcuts import render, get_object_or_404
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from .models import *
def index(request):
news = Content.objects.filter(is_published=True)
page = request.GET.get('page', 1)
paginator = Paginator(news, 20)
try:
page_obj = paginator.page(page)
except EmptyPage:
page_obj = paginator.page(1)
except PageNotAnInteger:
page_obj = paginator.page(paginator.num_pages)
return render(request, 'content/index.html', {'news': news, 'page_obj': page_obj})
def view_news(request, news_id):
news_item = get_object_or_404(Content, id=news_id)
return render(request, 'Content/view_news.html', {'news_item': news_item})
And there is my paginator template:
{% block content %}
<nav class="paginator">
<ul class="pagination">
{% if page_obj.has_previous %}
<a class="page-link" href="?page={{ page_obj.previous_page_number }}">
<li class="page-item">Предыдущая</li>
</a>
{% else %}
<a class="page-link">
<li class="page-item">Предыдущая</li>
</a>
{% endif %}
{% for i in page_obj.paginator.page_range %}
{% if page_obj.number == i %}
<a class="page-link">
<li class="page-item">{{ i }}</li>
</a>
{% else %}
<a class="page-link" href="?page={{ i }}">
<li class="page-item">{{ i }}</li>
</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="page-link" href="?page={{ page_obj.next_page_number }}">
<li class="page-item">Следующая</li>
</a>
{% else %}
<a class="page-link">
<li class="page-item">Следующая</li>
</a>
{% endif %}
</ul>
</nav>
{% endblock %}
Help me please with this problem
I have tried something like this in views.py:
class HomePage(TemplateView):
template_name = "clouderp/index.html"
def get_context_data(self, **kwargs):
context = super(HomePage, self).get_context_data(**kwargs)
qs = Blog.objects.all()
context['blog_list'] = qs
page = self.request.GET.get('page')
paginator = Paginator(qs, 4)
try:
users = paginator.page(page)
except PageNotAnInteger:
users = paginator.page(1)
except EmptyPage:
users = paginator.page(paginator.num_pages)
context['users'] = users
return context
And in template:
{% if users.has_other_pages %}
<ul class="pagination">
{% if users.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in users.paginator.page_range %}
{% if users.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only"></span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if users.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
I have created a blog application using django
I want to show all my blogs in my main index.html page and also wanted to do pagination for the blogs in my index page...
I was wondering how to do it...
Because the process I have done the blogs are not paginated according to 4 at a time...
Please try this code as below:
in views.py code
class BookListView(ListView):
model=Book
paginate_by=10
template_name='book/book_list.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
print (context)
paginator = context['paginator']
page_numbers_range = 10 # Display 5 page numbers
max_index = len(paginator.page_range)
page = self.request.GET.get('page')
print (self.request)
current_page = int(page) if page else 1
start_index = int((current_page - 1) / page_numbers_range) * page_numbers_range
end_index = start_index + page_numbers_range
if end_index >= max_index:
end_index = max_index
page_range = paginator.page_range[start_index:end_index]
context['page_range'] = page_range
return context
book_list = BookListView.as_view()
and the template:
<div class="container">
<!-- Pagination -->
{% if is_paginated %}
<nav>
<ul class="pagination justify-content-center" style="margin:20px 0">
{% if page_obj.has_previous %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.previous_page_number }}">
<span>Prev</span>
</a>
</li>
{% else %}
<li class="disabled page-item">
<a class="page-link" href="#">
<span>Prev</span>
</a>
</li>
{% endif %}
{% for page in page_range %}
<li {% if page == page_obj.number %} class="active page-item" {% endif %}>
<a class="page-link" href="?page={{ page }}">{{ page }}</a>
</li>
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a class="page-link" href="?page={{ page_obj.next_page_number }}">
<span>Next</span>
</a>
</li>
{% else %}
<li {% if not page_obj.has_next %}class="disabled page-item"{% endif %}>
<a class="page-link" href="#">
<span>Next</span>
</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
I want to print the subcategory names of each Main Category. The below code is now showing all subcategories for every Main category. How can I do?
index.html
{% for mainCatList in main_cat_list %}
<li class="subMenu"><a>{{ mainCatList.main_category_name }}</a>
<ul>
{% for subCat in cat_list %}
<li><i class="icon-chevron-right"></i>{{ subCat.category_name }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
views.html
from django.shortcuts import render
from .models import Product, Category, Main_Category
def homePageView(request):
main_cat_list = Main_Category.objects.all()
cat_list = Category.objects.all()
context = {'main_cat_list': main_cat_list, 'cat_list': cat_list}
return render(request, 'index.html', context)
I assume that your Category has foreign key to Main_Catagory. In that case, you can do this
{% for main_cat in main_cat_list %}
<li class="subMenu"><a>{{ main_cat.main_category_name }}</a>
<ul>
{% for sub_cat in main_cat.category_set.all %}
<li><i class="icon-chevron-right"></i>{{ sub_cat.category_name }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
I am new to django.
I have a django template that renders mongodb values and accordingly paints the html. I am using pagination and search to display records.
Problem: How should I query search input in my html to display all the records which is currently masked with pagination in django.
This is how it looks with pagination.
And this is how I want to display with pagination
This is my code:
def index(request):
values = data.find()
paginator = Paginator(values, 12)
page = request.GET.get('page')
try:
listItem = paginator.page(page)
except PageNotAnInteger:
listItem = paginator.page(1)
except EmptyPage:
listItem = paginator.page(paginator.num_pages)
return render(request, 'product.html', {"values":values, "listItem":listItem})
This is my html
{% block content %}
<ul class="row catalog-list">
{% for value in values %}
<li class="col-xs-12 col-sm-6 col-md-4 col-lg-4">
<div>
<img src={{value.image_url_medium}}>
</div>
<div>
<h4 class="ellipsis-text catalog-item-name" tooltip={{value.name}}>{{value.name}}</h4>
<h5>Product Id: {{value.id_product}}</h5>
<h5>Category: {{value.catagory}}</h5>
<h5>Best Price: {{value.best_price}}</h5>
<h5>Best Price Vendor: {{value.best_price_vendor}}</h5>
<h5 class="ellipsis-text">Link:
<a href={{value.best_price_vendor_url}}>{{value.best_price_vendor_url}}</a>
</h5>
</div>
</li>
{% endfor %}
</ul>
<ul class="pagination">
<li class="step-links">
{% if listItem.has_previous %}
Previous
{% endif %}
<span class="current">
Page {{ listItem.number }} of {{ listItem.paginator.num_pages }}.
</span>
{% if listItem.has_next %}
Next
{% endif %}
</li>
</ul>
{% endblock %}
and jQuery:
$itemList = $('.catalog-list li');
console.log($itemList.length); //Prints 12
$("#filter").keyup(function(){
var filter = $(this).val();
if(filter==null){
$itemList.hide();
return;
}
var regex = new RegExp(filter, "i");
$itemList.each(function(){
if ($(this).find('h4').text().search(regex) < 0 && $(this).find('h5').text().search(regex) < 0) {
$(this).hide();
} else {
$(this).show();
}
});
});
I was new to django that time.
Its actually pretty simple here.
views.py
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from pymongo import MongoClient
register = template.Library()
port = 27017
client = MongoClient(port=port)
def people(request):
values = client.sdkUserIdDB.userIdColl.find() #getting all values from a database.
paginator = Paginator(values, 12) #putting all the values as a 12 slice so each page as 12 items from database.
page = request.GET.get('page')
try:
listItem = paginator.page(page)
except PageNotAnInteger:
listItem = paginator.page(1)
except EmptyPage:
listItem = paginator.page(paginator.num_pages)
return render(request, 'page.html', {"listItem":listItem})
templates > page.html
<ul class="pagination">
<li class="step-links">
{% if listItem.has_previous %}
Previous
{% endif %}
<span class="current">Page {{ listItem.number }} of {{ listItem.paginator.num_pages }}.</span>
{% if listItem.has_next %}
Next
{% endif %}
</li>
</ul>
have a table with websites and a many to one table with descriptions
trying to get a list, firstly getting the latest descriptions and then displaying them ordered by the content of the descriptions...
have the following in views.py
def category(request, category_name_slug):
"""Category Page"""
context_dict = {}
try:
category = Category.objects.get(slug=category_name_slug)
subcategory = SubCategory.objects.filter(category=category)
websites = Website.objects.filter(sub_categories=subcategory, online=True, banned=False)
sites = websites
descriptions = WebsiteDescription.objects.prefetch_related("about")
descriptions = descriptions.filter(about__in=sites)
descriptions = descriptions.order_by('about', '-updated')
descs = []
last_site = "" # The latest site selected
# Select the first (the latest) from each site group
for desc in descriptions:
if last_site != desc.about.id:
last_site = desc.about.id
desc.url = desc.about.url
desc.hs_id = desc.about.id
desc.banned = desc.about.banned
desc.referral = desc.about.referral
descs.append(desc)
context_dict['descs'] = descs
context_dict['websites'] = websites
context_dict['subcategory'] = subcategory
context_dict['category'] = category
except SubCategory.DoesNotExist:
pass
return render(request, 'category.html', context_dict)
this gives me a list with sites and their latest descriptions, so i have the following in category.html
{% if category %}
<h1>{{ category.name }}</h1>
{% for subcategory in category.subcategory_set.all %}
{{ subcategory.name }} ({{ subcategory.website_set.all|length }})
{% endfor %}
{% if descs %}
{% load endless %}
{% paginate descs %}
{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo" %}
<ul id='list' class='linksteps'>
<a href="/{{ desc.about_id }}" rel="nofollow" target="_blank">
<img src="/static/screenshots/{{ desc.about_id }}.png" />
</a>
<li><h3>{{ desc.about_id }}{% if desc.title %} - {{ desc.title }} {% endif %}</h3>
{% if desc.description %}<b>Description: </b>{{ desc.description }}
<br />{% endif %} {% if desc.subject %}<b>Keywords: </b>{{ desc.subject }}
<br />{% endif %} {% if desc.type %}<b>Type: </b>{{ desc.type }}
<br />{% endif %} {% if desc.officialInfo %} {% if desc.language %}<b>Language: </b>{{ desc.language }}
<br />{% endif %} {% if desc.contactInformation %}<b>Contact info: </b>{{ desc.contactInformation }}
<br />{% endif %}
{% else %}
{% endif %}
</li>
</ul>
</div>
{% endfor %}
{% show_pages %}
{% else %}
<strong>No websites currently in category.</strong>
{% endif %}
{% else %}
The specified subcategory {{ category_name }} does not exist!
{% endif %}
Initially i used dictsort
{% for desc in descs|dictsortreversed:"description"|dictsortreversed:"officialInfo"|dictsortreversed:"referral" %}
to give me the list in the desired order, so i was all happy ;)
Then however i decided i needed some pagination because the lists became too long.
django-endless-pagination works fine and does what its supposed too, however it splits up my list before the dictsort kicks in.
is there a way to sort before pagination happens and after i ordered_by at the initial query to have the latest descriptions selected?
much obliged
EDIT:
not getting any answers so my question might not be clear.
as far as i understand i need to sort the values in context_dict at the end in views.py replacing the dictsort as in the template
SOLVED:::
doing this did the trick for me to replace the dictsort.
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1
SOLVED:::
doing this did the trick for me to replace the dictsort.
descs1 = sorted(descs, key=operator.attrgetter('referral', 'officialInfo', 'description'), reverse=True)
context_dict['descs'] = descs1