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>
Related
I'm using django-filter with pagination, as long as the search filed is in the first place in filter.py -> fields = ['name_procss','typeLevel'] list, the pagination for filter of that filed will not work.
fitler.py:
import django_filters
from MyCore.models import MyRunStats
class MyRunStatsFilter(django_filters.FilterSet):
def gen_choice(self,filed):
return tuple((l, l) for l in list(MyRunStats.objects.exclude(**{filed: None}).values_list(filed, flat=True).distinct()))
name_procss = django_filters.ChoiceFilter(label='Process',choices=tuple,null_label='None',null_value='null')
typeLevel = django_filters.ChoiceFilter(label='Message Type',choices=tuple,null_label='None',null_value='null')
class Meta:
model = MyRunStats
fields = ['name_procss','typeLevel']
def __init__(self, *args, **kwargs):
super(MyRunStatsFilter, self).__init__(*args, **kwargs)
self.filters['name_procss'].extra['choices'] = self.gen_choice('name_procss')
self.filters['typeLevel'].extra['choices'] = self.gen_choice('typeLevel')
Views.py
def runstat_hist_view_render(request):
all_obj = MyRunStats.objects.all().order_by('-create_dttm')
hist_filter = MyRunStatsFilter(request.GET, queryset=all_obj)
paginator= Paginator(hist_filter.qs[:57], 20)
page = request.GET.get('page')
try:
response = paginator.page(page)
except PageNotAnInteger:
response = paginator.page(1)
except EmptyPage:
response = paginator.page(paginator.num_pages)
context = {'response': response,'filter': hist_filter}
return render(request, 'My/My_runstat_hist.html',context)
html:
<form method="get" >
{{ filter.form}}
<button type="button" onclick="submitFilter()" id="hist-search-button" >Search Message</button>
</form>
{% for item in response %}
<nav>
<ul class="pagination">
{% if response.has_previous %}
<li>« First</li>
<li >Previous</li>
{% else %}
<li>Previous</li>
{% endif %}
{% for num in response.paginator.page_range %}
{% if response.number == num %}
<li>{{num}}</li>
{% elif num > response.number|add:'-3' and num < response.number|add:'3' %}
<li>{{num}}</li>
{% endif %}
{% endfor %}
{% if response.has_next %}
<li>Next</li>
<li>Last »</li>
{% else %}
<li>Next</li>
{% endif %}
</ul>
</nav>
The issue is ,no matter which item is in the first place in filter.py->fields = ['name_procss','typeLevel'],for example now the 'name_procss' is in the first place ,then the pagination for 'name_procss' not work,if I put 'typeLevel' in the first place ,then pagination for 'typeLevel' will not work but for 'name_procss' will work.
def allProductCat(request, c_slug=None):
c_page = None
products_list = None
if c_slug is not None:
c_page = get_object_or_404(Category, slug=c_slug)
products_list = Product.objects.all().filter(category=c_page, available=True)
else:
products_list = Product.objects.all().filter(available=True)
paginator = Paginator(products_list, 6)
try:
page = int(request.GET.get('page', '1'))
except:
page = 1
try:
products = paginator.page(page)
except(EmptyPage, InvalidPage):
products = paginator.page(paginator.num_pages)
return render(request, "category.html", {'category': c_page, 'product': products})
// Code for Html //
<div class="mx-auto">
{% if product.paginator.num_page %}
<hr>
<div class="text-center">
{% for pg in product.paginator.page_range %}
{{pg}}
{% endfor %}
</div>
{% endif %}
</div>
when i add all these codes pagination doesnt shows up anything when i type the links to next page manually its working perfectly i dont understand whats wrong in this code, also these div doesnt shows anything inside it when i type anything...
====== views.py =======
from django.core.paginator import Paginator
def HomeView(request):
show_data = VehicleModel.objects.all() # Queryset For pagiantion
# Pagination code start
paginator = Paginator(show_data, 3, orphans=1)
page_number = request.GET.get('page')
show_data = paginator.get_page(page_number)
# Pagination code end
context = {'page_number':page_number}
return render(request,'dashboard.html',context)
======= in HTML ==========
# <!-- Pagination Block with page number -->
<div class="container mt-5">
<div class="row float-right ">
<span class="m-0 p-0">
{% if show_data.has_previous %} # <!-- For Previous Button -->
<a class="btn btn-outline-info" href="?page={{show_data.previous_page_number}}&ok=#ok">Previous</a>
{% endif %}
<span>{% for pg in show_data.paginator.page_range %} # <!-- For Page Numbers Buttons -->
{% if show_data.number == pg %}
<a href="?page={{pg}}" class="btn btn-sm btn-primary">
<span class="badge">{{pg}}</span>
</a>
{% else %}
<a href="?page={{pg}}" class="btn btn-sm btn-secondary">
<span class="badge">{{pg}}</span>
</a>
{% endif %}
{% endfor %}</span>
{% if show_data.has_next %} # <!-- For Next Button -->
<a class="btn btn-outline-info" href="?page={{show_data.next_page_number}}&ok=#ok">Next</a>
{% endif %}
</span>
</div>
</div>
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 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
for some reason my paginators not working properly on my post_list page, but it works for my tags_list_page and its almost identical. It wont display the number of pages. Heres my code for them
post list.html pagination
<div class="text-center" style="margin-bottom: 20px">
<ul class="pagination">
{% if object_list.has_previous %}
<li><<</li>
<li><a href="?{{ page_request_var }}={{ object_list.previous_page_number }}
{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">prev</a></li>
{% endif %}
{% for i in paginator.page_range %}
<li {% if page_obj.number == i %} class="active" {% endif %}>{{i}}<li>
{% endfor %}
{% if object_list.has_next %}
<li><a href="?{{ page_request_var }}={{ object_list.next_page_number }}
{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">next</a></li>
<li>>></li>
{% endif %}
</ul>
tags list.html pagination
<div class="text-center" style="margin-bottom: 20px">
<ul class="pagination">
{% if queryset.has_previous %}
<li><<</li>
<li><a href="?{{ page_request_var }}={{ queryset.previous_page_number }}
{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">prev</a></li>
{% endif %}
{% for i in paginator.page_range %}
<li {% if page_obj.number == i %} class="active" {% endif %}>{{i}}<li>
{% endfor %}
{% if queryset.has_next %}
<li><a href="?{{ page_request_var }}={{ queryset.next_page_number }}
{% if request.GET.q %}&q={{ request.GET.q }}{% endif %}">next</a></li>
<li>>></li>
{% endif %}
</ul>
my views
def post_list(request):
today = timezone.now().date()
queryset_list = Post.objects.active()
if request.user.is_staff or request.user.is_superuser:
queryset_list = Post.objects.all()
paginator = Paginator(queryset_list, 8)
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
queryset = paginator.page(1)
except EmptyPage:
queryset = paginator.page(paginator.num_pages)
template = "posts/post_list.html"
name = "user"
count = queryset_list.count()
context = {
"object_list": queryset,
"name": name,
"page_request_var": page_request_var,
"today": today,
"count": count
}
return render(request, template, context)
def tag_list(request, slug=None):
today = timezone.now().date()
instance = get_object_or_404(Tag, slug=slug)
ins = instance.post_set.all()
queryset_list = Post.objects.active()
if request.user.is_staff or request.user.is_superuser:
queryset_list = ins
paginator = Paginator(queryset_list, 9)
page_request_var = "tags"
page = request.GET.get(page_request_var)
try:
queryset = paginator.page(page)
except PageNotAnInteger:
queryset = paginator.page(1)
except EmptyPage:
queryset = paginator.page(paginator.num_pages)
hey = paginator.num_pages
kount = queryset_list.count()
name = "Tags list"
context = {
"queryset": queryset,
"paginator": paginator,
"page_request_var": page_request_var,
"hey": hey,
"title": "posts",
"name": name,
"today": today,
"kount": kount
}
return render(request, "posts/tag_list.html", context)
It works for the tags pagination fine as I said. dont know whats going on
It was working fine. Any help is appreciated
You're not passing the paginator to the template in the post_list view.