How load to Django Paginator Page (next/ previous)? - django

Hy,
i followed a tutorial for a multiple model search and it worked. now i want to paginate the output. But how can i load my paginator page (next/ previous) data into my template? So far if i push next i get an error.
views.py
from django.views.generic import TemplateView, ListView
from django.views.generic import View
from django.shortcuts import render
from django.db.models import Q
from django.core.paginator import Paginator
from itertools import chain
# --- Import Models
from datainput.models import Animal
from datainput.models import Farmer
<....>
class SearchView(ListView):
template_name = 'farmapi/searchview.html'
paginate_by = 2
count = 0
def get_context_data(self, *args, **kwargs):
context = super().get_context_data(*args, **kwargs)
context['count'] = self.count or 0
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self):
request = self.request
query = request.GET.get('q', None)
if query is not None:
farmer_results = Farmer.objects.search(query)
animal_results = Animal.objects.search(query)
# combine querysets
queryset_chain = chain(
farmer_results,
animal_results
)
qs = sorted(queryset_chain,
key=lambda instance: instance.pk,
reverse=True)
self.count = len(qs) # since qs is actually a list
return qs
return Farmer.objects.none() # just an empty queryset as default
template.html
{% extends 'base.html' %}
{% load class_name %}
{% load static %}
{% block custom_css %}
<link rel="stylesheet" type="text/css" href="{% static 'css/home_styles.css' %}">
{% endblock %}
{% block content %}
<div style="height: 10px;">
</div>
<div class="container-fluid">
<div class='row'>
<div class="col-4 offset-md-8">
<form method='GET' class='' action='.'>
<div class="input-group form-group-no-border mx-auto" style="margin-bottom: 0px; font-size: 32px;">
<span class="input-group-addon cfe-nav" style='color:#000'>
<i class="fa fa-search" aria-hidden="true"></i>
</span>
<input type="text" name="q" data-toggle="popover" data-placement="bottom" data-content="Press enter to search" class="form-control cfe-nav mt-0 py-3" placeholder="Search..." value="" style="" data-original-title="" title="" autofocus="autofocus">
</div>
</form>
</div>
</div>
</div>
<div style="height: 10px;">
</div>
<div class="container-fluid">
<div class="row">
<div class="col-6 offset-md-4">
{% for object in object_list %}
{% with object|class_name as klass %}
{% if klass == 'Farmer' %}
<div class='row'>
Farmer: <a href='{{ object.get_absolute_url }}'> {{ object.first_name }} {{ object.last_name }}</a>
</div>
{% elif klass == 'Animal' %}
<div class='row'>
Animal: <a href='{{ object.get_absolute_url }}'> {{ object.name }} {{ object.species }}</a>
</div>
{% else %}
<div class='row'>
<a href='{{ object.get_absolute_url }}'>{{ object }} | {{ object|class_name }}</a>
</div>
{% endif %}
{% endwith %}
{% empty %}
{% endfor %}
<div style="height: 10px;">
</div>
<div class='row'>
<results>{{ count }} results for <b>{{ query }}</b></results>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<!-- Pagniator Data -->
<div class="paginator">
<span class="step-links">
<span class="current">
Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}.
</span>
{% if page_obj.has_previous %}
« first
previous
{% endif %}
{% if page_obj.has_next %}
next
last »
{% endif %}
</span>
</div>
</div>
{% endblock %}
if i my template shows me for instance "4 Results for xyz" and "Page 1 of 2" and i push next or last Page, then i get this Error Message:
Page not found (404) Request Method: GET Request URL:
http://127.0.0.1:8000/data/searchview/?page=2 Raised by:
farmapi.views.SearchView
Invalid page (2): That page contains no results
So as far as i understand i have to explicit paginate the return of my queryset so that the paginator will put it into? Or did i miss to set a request for the paginator?

I also use a paginator where the number of items per page can be defined by the user. I added following method:
def get_paginate_by(self, queryset):
limit = int(self.request.POST.get('limit', 25))
return limit
In the template it looks like:
{% if is_paginated %}
{{ page_obj|render_paginator }}
{% endif %}
where render_paginator a template tag is.
In your template call a url like: your_url?page=2

Related

Adding a tag to a pagination element django

When creating a pagination, everything works as it should. Added (?page= page number selection) pagination.
How can I add the pagination page number to its object?
When selecting an object and reloading the page, I need it to be spelled out in the URL (/?page=pagination number).
And the pagination remained on the selected page.
class MovieShow(DetailView):
model = Movie
template_name = 'movies/movie_play.html'
context_object_name = 'movie'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['object_list'] = Movie.objects.filter(course__slug=self.kwargs['course_slug'])
context['title'] = context['movie']
paginator = Paginator(context['object_list'], 1)
page = self.request.GET.get('page')
try:
context['object_list'] = paginator.page(page)
except PageNotAnInteger:
context['object_list'] = paginator.page(1)
except EmptyPage:
context['object_list'] = paginator.page(paginator.num_pages)
return context
This is how I present pagination in the template
<div class="pagination" id="pagination">
<span class="step-links" >
{% if object_list.has_previous %}
<a class="page-link" href="?page=1"> << </a>
<a class="page-link" href="?page={{ object_list.previous_page_number }}"> < </a>
{% endif %}
<span class="current">
{{ object_list.number }} из {{ object_list.paginator.num_pages }}
</span>
{% if object_list.has_next %}
<a class="page-link" href="?page={{ object_list.next_page_number }}"> > </a>
<a class="page-link" href="?page={{ object_list.paginator.num_pages }}"> >> </a>
{% endif %}
</span>
And so I have a search of the elements inside the pagination, on which I want to hang the pagination page number.
I really hope I asked the question correctly.
I will be glad of any help!
<div class="video_courses" id="block-posts">
{% for c in object_list %}
<a class="a_hover" href="{{ c.get_absolute_url }}">
<div class="video_courses_block">
<div class="video_courses_block_img"><img src="{{ c.poster.url }}" alt=""></div>
<div class="video_courses_block_text">
<div class="video_courses_block_text_title"><h2>[ {{ c.author }} ] {{ c.title }}</h2></div>
<div class="video_courses_block_text_navigation">
<div class="video_courses_block_text_left">{{ c.category }}</div>
<div class="video_courses_block_text_rig">{{ course.movie_set.count }}</div>
</div>
</div>
</div>
</a>
{% endfor %}
{% include 'pagination.html' %}
You just need to add if to the link and specify the page number
{% for c in object_list %}
{% if object_list.number %}
<a class="a_hover" href="{{ c.get_absolute_url }}?page={{ object_list.number }}">
{% endif %}
<div class="video_courses_block">
<div class="video_courses_block_img"><img src="{{ c.poster.url }}" alt=""></div>
<div class="video_courses_block_text">
<div class="video_courses_block_text_title">
<h2>[ {{ c.author }} ] {{ c.title }}</h2>
</div>
<div class="video_courses_block_text_navigation">
<div class="video_courses_block_text_left">{{ c.category }}</div>
<div class="video_courses_block_text_rig">{{ course.movie_set.count }}</div>
</div>
</div>
</div>
</a>
{% endfor %}
</div>
{% include 'pagination.html' %}

Django: Certain users get random 404 error

I'm facing a strange issue that I can't handle on my own.
In normal cases when users click on a link, then they are directed to a page where they can edit their hook baits (objects). However, certain users get 404 errors, but I don't know why because the page is rendered for most users.
html where the link is
<div class="row justify-content-center mx-2" >
<div class="col-12 p-0">
<ul class="list-group text-center custom-borders m-2 p-0">
{% if own_hookbaits.count == 0 %}
<a href="{% url 'user_profile:hookbaits' request.user.fisherman.fisherman_id %}" class="list-group-item" >No hook baits yet</a>
{% else %}
{% for hookbait in own_hookbaits %}
{{ hookbait.name }}
{% endfor %}
{% endif %}
</ul>
</div>
views.py
class HookBaitUpdateView(UpdateView):
model = HookBait
template_name = "user_profile/hookbaits.html"
form_class = HookBaitForm
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['formset'] = HookBaitFormset(queryset=HookBait.objects.filter(fisherman=self.request.user.fisherman))
return context
def post(self, request, *args, **kwargs):
formset = HookBaitFormset(request.POST)
if formset.is_valid():
return self.form_valid(formset)
else:
return self.form_invalid(formset)
def form_valid(self, formset):
instances = formset.save(commit=False)
for instance in instances:
instance.fisherman = self.request.user.fisherman
instance.save()
return super().form_valid(formset)
def form_invalid(self, formset):
return HttpResponse("Invalid")
def get_success_url(self):
return reverse('user_profile:profile', args=(self.kwargs['pk'],))
urls.py
app_name = "user_profile"
urlpatterns = [
path("profile/<int:pk>/", views.ProfileView.as_view(), name="profile"),
path("profile/<int:pk>/hookbaits/", views.HookBaitUpdateView.as_view(), name="hookbaits"),
]
rendered html
<div class="row justify-content-center m-0">
<div class="col-12 col-md-6 col-lg-4 p-0">
<div class="row mx-3 my-3 justify-content-center text-center">
<div class="card p-2 custom-borders">
<div class="card-body p-2">
<form method="POST">
{% csrf_token %}
<table class="d-flex justify-content-center">
{{ formset.management_form }}
{% for form in formset %}
<tr class="formset_row">
{% for field in form.visible_fields %}
<td class="pb-2">
{% if form.instance.pk %}{{ form.DELETE }}{% endif %}
{% if forloop.first %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% endif %}
{{ field.errors }}
{{ field }}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
<input type="submit" class="btn btn-primary w-50 mt-1" style="background-color: #00754B;" value="Mentés">
</form>
</div>
</div>
</div>
</div>
</div>
Any suggestions what the solution would be? Thanks!
there are some possibilities
the wrong link clicked like if your trying access this URL profile/25/hookbaits/
and in the data index there is no HookBait with the id of 25
in HookBaitUpdateView you are trying to get queryset=HookBait.objects.filter(fisherman=self.request.user.fisherman)
maybe there is no hookbait associate with user.fisherman
404 page mostly served when you call get_object_or_404(HookBait, pk=25)
and update view may call this method

Django search pagination error, page not found error each time I try to move to page 2

I'm popping up with an error on my comic book ecommerce application. It's a Django app. Basically, the search function isn't paginating properly, giving me a page not found error each time I try to move to page 2 and onwards. It works fine in my general products listing area though, where there is no q-based search.
It works fine when I paginate just the products section, adding in...
paginate_by = 6
...into the class ListView section...
...and adding this section into the view.html section...
<div class="pagination">
<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>
...But, once I try to paginate the search function in the same way, it appears to paginate, but page 2 and onwards just gives me a page not found error...
http://127.0.0.1:8000/search/?page=2
Request Method: GET
Request URL: http://127.0.0.1:8000/search/?page=2
Raised by: search.views.SearchProductView
....I think it has something to do with q, and the view.html section, but I'm not sure.
Any help would be much-appreciated.
Also, here's my view.html:
{% extends "base.html" %}
{% block content %}
<!-- <div class="pagination">
<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> -->
<!--the heading with the result of the name-->
<div class="row mb-3">
{% if query %}
<div class="col-12">
Results for <b>{{ query }}</b>
<hr/>
</div>
{% else %}
<div class="col-12 col-md-8 mx-auto py-5">
{% include 'search/snippets/search-form.html' %}
</div>
<div class="col-12">
<hr>
</div>
{% endif %}
</div>
<!--create a card/item for each comic-->
<div class="row">
{% for obj in object_list %}
<div class="col">
{% include 'products/snippets/card.html' with instance=obj %}
{% if forloop.counter|divisibleby:3 %}
</div>
</div>
<!--or else if no item just create a blank row and column-->
<div class='row'><div class='col-12'><hr/></div>
{% else %}
</div>
{% endif %}
{% endfor %}
{% endblock %}
And here's a snippet that works within the view.html (search-form.html)
<form method="GET" action='{% url "search:query" %}' class="form my-2 my-lg-0 search-form">
<div class="input-group">
<input class="form-control" type="search" placeholder="Search" name='q' aria-label="Search" value='{{ request.GET.q }}'>
<span class='input-group-btn'>
<button class="btn btn-outline-success" type="submit">Search</button>
</span>
</div>
</form>
As well, here's my view.py backend:
from django.shortcuts import render
from django.views.generic import ListView
from products.models import Product
from django.core.paginator import Paginator
class SearchProductView(ListView):
#PROBLEM WITH PAGINATION IN THE SEarch function and view
#https://stackoverflow.com/questions/48436649/django-pagination-page-not-found?rq=1
#https://www.youtube.com/watch?v=acOktTcTVEQ
#https://www.youtube.com/watch?v=q-Pw7Le30qQ
#https://docs.djangoproject.com/en/3.1/topics/pagination/
#paginate_by = 6
template_name = "search/view.html"
def get_context_data(self, *args, **kwargs):
context = super(SearchProductView, self).get_context_data(*args, **kwargs)
context['query'] = self.request.GET.get('q')
return context
def get_queryset(self, *args, **kwargs):
request = self.request
method_dict = request.GET
query = method_dict.get('q', None) #method_dict['q']
if query is not None:
return Product.objects.search(query).order_by('title')
return Product.objects.filter(featured=True).order_by('title')
'''
__icontains = field contains this
__iexact = field is exactly this
'''
Finally, here are my urls:
from django.conf.urls import url
from .views import (
SearchProductView
)
urlpatterns = [
url(r'^$', SearchProductView.as_view(), name='query'),
]

why when I click a different user returns me back to the current request user?

sorry, I had to take some screenshots to explains what is going on with me. now, I have much profile that has many different users and when I log in with one of it I'll assume the username is: medoabdin like you find on the screenshot now (medoabdin) and the name of it is (Origin) for me is a current user request. so, now I have also many different questions created by the different users, and when I want to enter any other profile let's suppose the user is (abdelhamedabdin) by current request user it returns me back to the current request (medoabdin) and not returns me back to abdelhamedabdin.
however, when I check the link URL I find the link is correct and when I log in with (abdelhamedabdin) user I see the same thing occurs to me against (medoabdin) so, can anyone tell me what is going on guys?
these are screenshots:
current request (medoabdin),
several questions,
show the link url for different users,
accounts/profile.html
{% extends 'base.html' %}
{% block title %} {{ user.first_name }} {{ user.last_name }} Profile {% endblock %}
{% block body %}
<!-- User Profile Section -->
{% if user.is_authenticated %}
<div class="profile">
<div class="container-fluid">
<div class="col-md-1">
<div class="thumbnail">
<div class="row">
<div class="col-xs-12">
<!-- Profile View Section -->
<div class="logo-image text-center">
{% if user.userprofile.logo %}
<div class="my-image">
{% if request.user.username == user.userprofile.slug %}
<a href="{% url 'accounts:user_image' user.userprofile.slug %}">
<img class="img-responsive" src="{{ user.userprofile.logo.url }}">
</a>
<span>
<a href="{% url 'accounts:add_avatar' user.userprofile.slug %}" class="fa fa-camera fa-1x text-center">
<p>Upload Image</p>
</a>
</span>
{% endif %}
</div>
{% else %}
{% load static %}
<div class="my-image">
<img class="img-responsive img-thumbnail" src="{% static 'index/images/default-logo.jpg' %}">
<span>
<a href="{% url 'accounts:add_avatar' user.userprofile.slug %}" class="fa fa-camera fa-1x text-center">
<p>Upload Image</p>
</a>
</span>
</div>
{% endif %}
{% if user.first_name != '' and user.last_name != '' %}
<h4>{{ user.first_name }} {{ user.last_name }}</h4>
{% else %}
<h4>User Profile</h4>
{% endif %}
</div>
</div>
<div class="col-xs-12">
<div class="caption">
<ul class="nav nav-pills nav-stacked">
<li role="presentation" class="active">Overview</li>
<li role="presentation" class="">Personal Information</li>
<li role="presentation" class="">Skills</li>
</ul>
</div>
</div>
</div>
</div>
</div>
<!-- Information Sections -->
<div class="col-md-8 col-md-offset-3 information">
<div class="overview show" id="overview">
<h2 class="line">Overview</h2>
<p class="lead">{{ user.userprofile.overview }}</p>
<a data-placement="bottom" title="update overview" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".overview_info"></a>
</div>
<div class="personal-info" id="personal-information">
<h2 class="line">Personal Information</h2>
<p class="lead">City: {{ user.userprofile.city }}</p>
<p class="lead">Phone Number: 0{{ user.userprofile.phone }}</p>
<p class="lead">Sex: {{ user.userprofile.sex }}</p>
<a data-placement="bottom" title="update personal information" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".personal_info"></a>
</div>
<div class="skill" id="my-skills">
<h2 class="line">Skills:</h2>
<p class="lead">{{ user.userprofile.skill }}</p>
<a data-placement="bottom" title="update skills" class="fa fa-edit" data-toggle="modal" data-tooltip="tooltip" data-target=".skills"></a>
</div>
</div>
<!-- get all questions -->
{% if user_prof.userasking_set.all %}
<div class="col-md-8 col-md-offset-3 user_questions">
<h2 class="line">All Questions You Asked</h2>
{% for questions in user_prof.userasking_set.all %}
<p>{{ questions.title }}</p>
{% endfor %}
</div>
{% endif %}
<!-- get favourites -->
{% if get_favourite %}
<div class="col-md-8 col-md-offset-3 user_questions">
<h2 class="line">Favourites</h2>
{% for fav in get_favourite %}
<p>{{ fav.title }}</p>
{% endfor %}
</div>
{% endif %}
</div>
{% include 'accounts/information_form.html' %}
</div>
{% include 'base_footer.html' %}
{% endif %}
{% endblock %}
accounts/views.py
#method_decorator(login_required, name='dispatch')
# view profile page
class ViewProfile(UpdateView):
queryset = UserProfile.objects.all()
template_name = 'accounts/profile.html'
form_class = UpdateInfoForm
slug_field = 'slug'
slug_url_kwarg = 'user_slug'
def get_success_url(self):
return reverse_lazy('accounts:view_profile', kwargs={'user_slug': self.request.user.userprofile.slug})
def get_context_data(self, **kwargs):
self.request.session['switch_comment'] = False
context = super().get_context_data(**kwargs)
user_prof = UserProfile.objects.get(user=self.request.user)
context['user_prof'] = user_prof
context['get_favourite'] = User.objects.get(username=self.request.user.username).favorite.all()
return context
def form_valid(self, form):
form.instance.user_slug = self.request.user.userprofile.slug
self.object = form.save()
return super().form_valid(form)
community/views.py
# List all questions + search
class UserQuestions(ListView):
template_name = 'community/user_questions.html'
context_object_name = 'all_objects'
queryset = UserAsking
def get_context_data(self, object_list=queryset, **kwargs):
context = super().get_context_data(**kwargs)
# paginator
context['all_objects'] = UserAsking.objects.all()
paginator = Paginator(context['all_objects'], 5)
page_number = self.request.GET.get('page_number')
context['all_objects'] = paginator.get_page(page_number)
# search
context['query'] = self.request.GET.get("query", '')
if context['query']:
all_objects = UserAsking.objects.all().order_by('-date')
context['all_objects'] = all_objects.filter(
Q(title__contains=self.request.GET['query']) |
Q(question__contains=self.request.GET['query']) |
Q(field__contains=self.request.GET['query'])
)
return context
community/user_questions.py
{% extends 'base.html' %}
{% block title %} All Questions That People Asked {% endblock %}
{% block body %}
{% if request.user.is_authenticated %}
<div class="all-questions">
<div class="container">
<div class="fl-left hidden-sm hidden-xs">
<h2>All Questions</h2>
</div>
<div class="fl-right hidden-sm hidden-xs">
Ask Question
</div>
<div class="clear"></div>
<div class="row">
<div class="add-q">
<div class="col-sm-12 visible-sm-block visible-xs-block">
<h2>All Questions</h2>
</div>
<div class="col-sm-12 visible-sm-block visible-xs-block">
Ask Question
</div>
</div>
{% if all_objects %}
<div class="col-sm-12">
<div class="questions">
{% for post in all_objects %}
<div class="q_section">
<a class="text-primary title" href="{% url 'community:question_view' post.ask_slug %}">{{ post.title }}</a>
<p class="field">{{ post.field }}</p>
<div class="info fl-right">
<span class="time">{{ post.date }}</span> |
<a href="{% url 'accounts:view_profile' post.userprofile.slug %}" style="font-size:14px">
{% if post.userprofile.user.first_name != '' %}
{{ post.userprofile.user.first_name }}
{% else %}
User
{% endif %}
<img class="logo-image" style="width:25px;height: 25px" src="
{% if request.user.userprofile.logo %}
{{ request.user.userprofile.logo.url }}
{% else %}
{% load static %}
{% static 'index/images/default-logo.jpg' %}
{% endif %}
">
</a>
</div>
<div class="">
<!--a class="btn btn-primary btn-lg" href="{# {% url 'community:delete_post' post.id %} #}">
<i class="fa fa-trash x2"></i>
</a-->
</div>
</div>
{% endfor %}
</div>
</div>
{% else %}
<h2 class="text-center text-info">No Questions</h2>
{% endif %}
</div>
<!-- Pagination -->
{% if all_objects %}
<div class="pagination">
<span class="step-links">
{% if all_objects.has_previous %}
« first
previous
{% endif %}
<span class="current">
Page {{ all_objects.number }} of {{ all_objects.paginator.num_pages }}.
</span>
{% if all_objects.has_next %}
next
last »
{% endif %}
</span>
</div>
{% endif %}
</div>
</div>
{% include 'base_footer.html' %}
{% endif %}
{% endblock %}

How to create a search function on a class-based list view?

I am trying to create a search function based on the title of my posts. Right now I am trying to implement this search using a filter but the list view is not rendering. I am unsure if I should implement a URL for my search function.
This is my model:
class Post(models.Model):
title = models.CharField(max_length=100)
image = models.ImageField(default = 'default0.jpg', upload_to='course_image/')
description = models.TextField()
price = models.DecimalField(decimal_places=2, max_digits=6)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
feedback = models.ManyToManyField(Feedback)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk' : self.pk})
This is my class-based list view:
class PostListView(ListView):
model = Post
template_name = 'store/sub_home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['date_posted']
paginate_by = 12
def get_queryset(self):
object_list = super(PostListView, self).get_queryset()
search = self.request.GET.get('q', None)
if search:
object_list = object_list.filter(title__icontains = title)
return object_list
This is my search bar:
<div id="search">
<form method='GET' action=''>
<input type="text" name='q' placeholder="">
<button id='search_holder'>
<img src="/static/store/search_icon.gif" id="search_icon">
</button>
</form>
</div>
This is my html that is rendering the posts:
{% extends "store/base.html" %}
{% block content %}
{% include "store/home_ext.html" %}
<div style="padding-top: 20px;" id="main" >
<section class="text-center mb-4">
<div class="row" id="random">
{% for post in posts %}
{% include "store/card.html" %}
{% endfor %}
</div>
<div class="row" id="subscription" style="display: none;">
{% if not subs %}
<h2>You have not subscribed to any course :/</h2>
{% endif %}
{% for post in subs %}
{% include "store/card.html" %}
{% endfor %}
</div>
<div class="row" id="content" style="display: none;">
{% if not mine %}
<h2>You have not published anything :/</h2>
{% endif %}
{% for post in mine %}
{% include "store/card.html" %}
{% endfor %}
</div>
</section>
{% include "store/pagination.html" %}
</div>
{% endblock content %}
This is my card.html:
{% load extra_filter %}
<div class="col-lg-3 col-md-6 mb-4">
<div id="course_card">
<div class="view overlay">
<img style="margin-left: -10px;" src="{{ post.image.url }}" alt="">
</div>
<div>
<div>
<strong>
{% if user.is_authenticated %}
<a class="title" href="{% url 'post-detail' post.id %}" >
{% else %}
<a class="title" href="{% url 'login' %}" >
{% endif %}
{% if post.title|length < 30 %}
<span>{{ post.title }}</span>
{% else %}
<span>{{ post.title|cut:27 }}</span>
{% endif %}
<span style="background-color: rgb(253, 98, 98);" class="badge badge-pill danger-color">NEW
</span>
</a>
</strong>
</div>
<div class="star-ratings-css">
<div class="star-ratings-css-top" style="width: {{ post.feedback|calc_rating }}%"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
<div class="star-ratings-css-bottom"><span>★</span><span>★</span><span>★</span><span>★</span><span>★</span></div>
</div>
<a href="{% url 'user-posts' post.author.username %}" class="author">
by {{ post.author }}
</a>
<div>
<strong style="text-align: right;" class="price">S${{ post.price }}
</strong>
</div>
<small class="date">
{{ post.date_posted|date:'d F y'}}
</small>
</div>
</div>
</div>
As Nalin Dobhal mentioned in comments, context_object_name should be posts not post. Because in template, you are iterating through posts context variable. Also, when using search functionality, the implementation should be like this:
class PostListView(ListView):
model = Post
template_name = 'store/sub_home.html' # /_.html
context_object_name = 'posts'
ordering = ['date_posted']
paginate_by = 12
def get_queryset(self, *args, **kwargs):
object_list = super(PostListView, self).get_queryset(*args, **kwargs)
search = self.request.GET.get('q', None)
if search:
object_list = object_list.filter(title__icontains = search)
return object_list
Because you are sending the search query through URL querystring(ie: url will look like /posts/?q=title in browser). I am using request.GET.get('q') to fetch those query string values, and use it to filter the queryset.