I'm working on my Django blog, and when I go to categories I listed all posts in that category, but for some reason I cannot manage to work pagination. Everything works except one thing, on all pages I can see all posts, but I want to see only 6 posts per page.
This is pagination.html that is included in category detail page
<div class="mb-30">
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-start">
{% if category_page.has_previous %}
<li class="page-item"><a class="page-link" href="?page={{ category_page.previous_page_number }}"><i class="ti-angle-left"></i></a></li>
{% else %}
<li class="page-item"><a class="page-link" href="#"><i class="ti-angle-left"></i></a></li>
{% endif %}
{% for i in category_page.paginator.page_range %}
{% if category_page.number == i %}
<li class="page-item active"><a class="page-link" href="#">{{ i }}</a></li>
{% else %}
<li class="page-item"><a class="page-link" href="?page={{ i }}">{{ i }}</a></li>
{% endif %}
{% endfor %}
{% if category_page.has_next %}
<li class="page-item"><a class="page-link" href="?page={{ category_page.next_page_number }}"><i class="ti-angle-right"></i></a></li>
{% else %}
<li class="page-item"><a class="page-link" href="#"><i class="ti-angle-right"></i></a></li>
{% endif %}
</ul>
</nav>
</div>
This is category_detail.html
{% for post in posts %}
<article class="col-lg-10">
<div class="background-white">
<div class="post-thumb">
<a href="{{ post.get_absolute_url }}">
<img class="border-radius" src="{{ post.image.standard.url }}" alt="">
</a>
</div>
<div class="pl-10">
<div class="mb-15">
<a class="meta-2" href="{{ post.category.get_absolute_url }}"><span class="post-in">{{ post.category}}</span></a>
</div>
<h5 class="mb-15">
{{ post.post_title }}</h5>
<p class="mb-30">{{ post.body | slice:":200" | safe }}</p>
<div class="mb-10">
<span class="post-on">{{ post.created_at}}</span>
</div>
</div>
</div>
</article>
{% endfor %}
{% include "include/pagination.html" %}
This is views.py
def category_detail(request, slug):
category = get_object_or_404(Category, slug=slug)
categories = Category.objects.all()
posts = Post.objects.filter(category=category)
paginator = Paginator(posts, 6)
page = request.GET.get('page')
try:
category_page = paginator.get_page(page)
except PageNotAnInteger:
category_page = paginator.get_page(1)
except EmptyPage:
category_page = paginator.get_page(paginator.num_pages)
context = {'category': category, 'categories': categories, 'category_page': category_page, 'posts':posts}
return render(request, 'category_detail.html', context)
Any idea why I see all post, but not only 6?
Change your category_detail.html
Docs: https://docs.djangoproject.com/en/4.1/topics/pagination/
{% for post in category_page %}
<article class="col-lg-10">
<div class="background-white">
<div class="post-thumb">
<a href="{{ post.get_absolute_url }}">
<img class="border-radius" src="{{ post.image.standard.url }}" alt="">
</a>
</div>
<div class="pl-10">
<div class="mb-15">
<a class="meta-2" href="{{ post.category.get_absolute_url }}"><span class="post-in">{{ post.category}}</span></a>
</div>
<h5 class="mb-15">
{{ post.post_title }}</h5>
<p class="mb-30">{{ post.body | slice:":200" | safe }}</p>
<div class="mb-10">
<span class="post-on">{{ post.created_at}}</span>
</div>
</div>
</div>
</article>
{% endfor %}
{% include "include/pagination.html" %}
I am working on a Django project that serves as a grocery store. I am trying to set it up so that when people click on checkboxes and press the confirm purchase button, then the values from the checkboxes will print to a new HTML template. The problem I am having is that when I go to the new template it doesn't print the values from the checkboxes.
Views.py
class PostListView(ListView):
model = Post
template_name = 'blog/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
def inventory(request):
products = request.POST.getlist('products')
for product in products:
a = Post.objects.get(title=product)
a.quantity = a.quantity -1
a.save()
print(products)
return render(request, 'blog/confirm.html')
Home.html
{% extends "blog/base.html" %}
{% block content %}
<form action="{% url 'inventory' %}" method="POST" id="menuForm">
{% for post in posts %}
{% if post.quantity > 0 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2">{{ post.category }}</a>
</div>
<h2><a class="article-title" >{{ post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
<input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }}
</input>
</div>
</article>
{% else %}
{% endif %}
{% endfor %}
<button type="submit" form="menuForm">Confirm Purchase</button>
</form>
{% endblock content %}
confirm.html
{% extends "blog/base.html" %}
{% block content %}
{% for post in posts %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2">{{ post.category }}</a>
</div>
<h2><a class="article-title" >{{ post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
<input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }}
</input>
</div>
</article>
{% endfor %}
{% endblock %}
urls.py
path('list/', PostListView.as_view(), name='blog-home'),
path('confirm', views.inventory, name='inventory'),
It's happening because of this you did not passed posts on confirm.html page
def inventory(request):
posts = Post.objects.get(title=product)
products = request.POST.getlist('products')
for product in products:
a = Post.objects.get(title=product)
a.quantity = a.quantity -1
a.save()
print(products)
return render(request, 'blog/confirm.html',{'posts':posts})
I am following django tutorial by #CoreyMSchafer. I got error while practicing i can't find solution to it.
According to my understanding its problem with reversing of url. but can't find out what is wrong
Error:
NoReverseMatch at /
Reverse for 'user-posts' with arguments '('',)' not found. 1 pattern(s) tried: ['user/(?P[^/]+)$']
For some reason error is in head of base.html where I'm linking bootstrap.
I also tried removing that link then its giving same error but at line 0 of base.html
views.py:
class UserPostListView(ListView):
model = Post
context_object_name = 'posts'
template_name = 'blog/user_posts.html'
paginate_by = 5
def get_queryset(self):
user = get_object_or_404(User, username=self.kwargs.get('username'))
return Post.objects.all().filter(author= user).order_by('-date_posted')
urls.py file:
from django.urls import path, include
from .views import PostListView, PostDetailView, PostCreateView, PostUpdateView, PostDeletelView, UserPostListView
from . import views
urlpatterns = [
path('', PostListView.as_view(), name='blog-home'),
path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
path('post/new/', PostCreateView.as_view(), name='post-create'),
path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
path('post/<int:pk>/delete/', PostDeletelView.as_view(), name='post-delete'),
path('about/', views.about, name='blog-about'),
]
user_posts.html:
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
{% endblock content %}
home.html
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-info mb-4" href="?page=1">First</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.previous_page_number }}">Previous</a>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<a class="btn btn-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<a class="btn btn-outline-info mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-info mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
post_detail.html
{% extends "blog/base.html" %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}" alt="">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted|date:"M d, Y"}}</small>
{% if object.author == user %}
<div>
<a class="btn btn-secondary btn-sm mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content %}
base.html
{% extends "blog/base.html" %}
{% block content %}
<article class="media content-section">
<img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}" alt="">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{ object.author }}</a>
<small class="text-muted">{{ object.date_posted|date:"M d, Y"}}</small>
{% if object.author == user %}
<div>
<a class="btn btn-secondary btn-sm mb-1" href="{% url 'post-update' object.id %}">Update</a>
<a class="btn btn-danger btn-sm mb-1" href="{% url 'post-delete' object.id %}">Delete</a>
</div>
{% endif %}
</div>
<h2 class="article-title">{{ object.title }}</h2>
<p class="article-content">{{ object.content }}</p>
</div>
</article>
{% endblock content %}
url(r'^user/(?P<username>\w{0,50})/$', UserPostListView.as_view(), name='user-posts'),
just add it in your url
not this
path('user/<str:username>/', UserPostListView.as_view(),name='user-posts'),
I had the same question before.
In your user_posts.html and base.html,
change all the name of the 'object' stuff to 'post'.
Example:
"object.author" -> "post.author",
"object.title" -> "post.title",
"object.author.username" -> "post.author.username"
that's a fix for me.
PS: Actually, u didn't post out the above mentioned part of the code. XD
In the urls.py file -
path('user/<str:username>/', UserPostListView.as_view(),name='user-posts'),
You forget to add backslash after <str:username>
i was watching the same course and i had the same problem.
following two steps made this work for me:
first make sure that you are referring to a correct HTML and then add a forward slash after your url like this:
path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'),
if it didnt work for you use url instead of path like this:
url(r'^user/(?P<username>\w{0,50})/$', UserPostListView.as_view(), name='user-posts'),
I had the same error . My mistake was I misspelled 'object' in this line posts_detail.html
<a class="mr-2" href="{%url 'user-posts' object.author.username %}">{{ object.author }}</a>
this might not be the reason for your error, but anyone else stuck with this error check for typos in your HTML files.
Replace post.author.username with post.author.
It helped me.
I ran into the same issue as well.
I found that replacing the following line in blog/urls.py:
urlpatterns = [
path('user/<str:username>/', UserPostListView.as_view(), name='user-posts'),
]
with
from django.urls import path, re_path # <- don't forget this import
urlpatterns = [
re_path(r'^user/(?P<username>\w{0,50})/$', UserPostListView.as_view(), name='user-posts'),
}
solved the issue.
I have a ListView page that is working well with pagination. I also have Django filter added to that page for filtering. The problem is pagination is working well but with Django filter it stops working. When the page loads paginate_by is not working. When the pagination is clicked the next page not working.
What am I doing wrong?
views.py
class JobsListView(ListView, FilterView):
# model = JobPost
queryset = JobPost.objects.all()
template_name = 'jobpost_list.html'
paginate_by = 3
# page_kwargs = 'page'
filterset_class = JobPostFilter
def get_queryset(self, *args, **kwargs):
if self.kwargs:
return JobPost.objects.filter(position=self.kwargs['position']).order_by('-created_at')
else:
query = JobPost.objects.all().order_by('-created_at')
return query
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['todays'] = date.today()
context['filter'] = JobPostFilter(self.request.GET, queryset=self.get_queryset())
return context
template
{% extends 'base.html' %}
{% load bootstrap4 %}
{% load fontawesome %}
{% block content %}
{% if messages %}
<div class="alert alert-success alert-dismissible fade show">
{% for m in messages %}
<li{% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ m }}</li>
<button type="button" class="close" data-dismiss="alert" aria-
label="Close">
<span aria-hidden="true">×</span>
</button>
{% endfor %}
</div>
{% endif %}
<div class="col-12">
<h1 class="text-center">Vacancies</h1>
</div>
<div class="row">
<div class="col-4">
<form method="get">
{% bootstrap_form filter.form %}
{% buttons %}
<button class="btn btn-primary" type="submit">Search {% fontawesome_icon
'search' %}</button>
{% endbuttons %}
</form>
</div>
<div class="col-8">
{% for job in filter.qs %}
<div class="joblists">
<h3><a href='{% url "jobpost_detail" job.slug %}'>{{ job.position }} </a> <a
href="{% url 'jobpost_update_form' job.slug %}">{% fontawesome_icon 'edit' %}
</a></h3>
<p>{{ job.description|safe|truncatewords:30 }}</p>
{% if job.location != '' %}
<p>{% fontawesome_icon 'location-arrow' %} <strong>{{ job.location }}
</strong>
</p>
{% endif %}
<p>{{ job.job_type }}</p>
{% if job.deadline != NULL and job.deadline > todays %}
<p>{% fontawesome_icon 'calendar' %} {{ job.deadline|timeuntil }} <small>to
deadline</small></p>
{% endif %}
{% if job.deadline > todays %}
<p>{% fontawesome_icon 'check-circle' color='green' %} Open</p>
{% elif job.deadline < todays %}
<p>{% fontawesome_icon 'times-circle' color='red' %} Closed</p>
{% endif %}
</div>
{% endfor %}
</div>
<div class="pagination">
{% if is_paginated %}
<hr>
<nav aria-label="Page navigation example">
<ul class="pagination justify-content-center pagination-sm">
{% if page_obj.has_previous %}
{% if not search %}
<li class="page-item">
<a class="page-link" href="{% url 'jobpost_list' %}?page={{
page_obj.previous_page_number }}" tabindex="-1">Previous</a>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="{% url 'jobpost_list' %}?{{search}}&page=
{{ page_obj.previous_page_number }}" tabindex="-1">Previous</a>
</li>
{% endif %}
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#" tabindex="-1">Previous</a>
</li>
{% endif %}
{% for object in page_obj.paginator.page_range %}
<li class="page-item"><a class="page-link" href="{% url 'jobpost_list'
%}?page={{ forloop.counter }}">{{ forloop.counter }}</a></li>
{% endfor %}
{% if page_obj.has_next %}
{% if not search %}
<li class="page-item">
<a class="page-link" href="{% url 'jobpost_list' %}?page={{
page_obj.next_page_number }}">Next</a>
</li>
{% else %}
<li class="page-item">
<a class="page-link" href="{% url 'jobpost_list' %}?{{search}}&page=
{{ page_obj.next_page_number }}">Next</a>
</li>
{% endif %}
{% else %}
<li class="page-item disabled">
<a class="page-link" href="#">Next</a>
</li>
{% endif %}
</ul>
</nav>
{% endif %}
</div>
{% endblock %}
in {% for job in filter.qs %} if you replace filter.qs with 'object_list' it pagination and filtering will work. BUT This won't have any records when the page loads initially without any filter params set in the url.
I am trying to figure out what can be done. Searching....
I am having some trouble getting a drilldown for mptt in my template.
I have the following model.
models.py
class Dimension_value(MPTTModel):
name = models.CharField(max_length = 200, null=True, blank = True, default = '')
parent = TreeForeignKey("self", on_delete=models.CASCADE, null=True, blank=True, related_name="children")
class MPTTMeta:
order_insertion_by = ['name']
def __str__(self):
return self.name
views.py
def show_dimensions(request):
return render(request, "accounts/dimension_detail.html", {'dimensions': Dimension_value.objects.all()})
template.py
{% extends 'base.html' %}
{% block head %}
{% endblock %}
{%block body%}
<div class="container-fluid">
<div class="card">
<div class="card-body">
<h2>My dimensions</h2>
{% load mptt_tags %}
{% drilldown_tree_for_node dimensions as drilldown cumulative count accounts.Dimension_value.name in game_count %}
{% for node,structure in drilldown|tree_info %}
{% if structure.new_level %}<ul><li>{% else %}</li><li>{% endif %}
{% if node == dimension %}
<strong>{{ node.name }}</strong>
{% else %}
{{ node.name }}
{% if node.parent_id == dimension.pk %}({{ node.game_count }}){% endif %}
{% endif %}
{% for level in structure.closed_levels %}</li></ul>{% endfor %}
{% endfor %}
</div>
</div>
<br>
<br>
<a class="btn btn-primary" href="{% url 'add_plan' %}" role="button">Add a plan</a>
<button onclick="goBack()" class = "btn btn-secondary">Go Back</button><br><br><a class="btn btn-primary" href="{% url 'subscribeusertoplan' %}" role="button">Add a user to plan</a>
</div>
{%endblock%}
I have added the view according to the documentation found here: https://django-mptt.readthedocs.io/en/latest/templates.html?highlight=examples#examples
However I get the following error.
Exception Type: AttributeError
Exception Value:
'TreeQuerySet' object has no attribute '_tree_manager'
Hope someone can nudge me in the right direction. Thanks!
You can do this by using some css and jquery
{% block head %}
{% endblock %}
{%block body%}
<div class="container-fluid">
<div class="card">
<div class="card-body">
<h2>My dimensions</h2>
{% load mptt_tags %}
{% recursetree dimensions %}
<a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse{{node.level}}" aria-expanded="false" aria-controls="collapsed">
{{ node.name }}</a>
{% if not node.is_leaf_node %}
<ul class="children">
<div id="collapse{{node.level}}" class="children panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
<div class="panel-body">
{{ children }} </div>
</div>
</ul>
{% endif %}
{% endrecursetree %}
</div>
</div>
<br>
<a class="btn btn-primary" href="{% url 'add_plan' %}" role="button">Add a plan</a>
<button onclick="goBack()" class = "btn btn-secondary">Go Back</button><br><br><a class="btn btn-primary" href="{% url 'subscribeusertoplan' %}" role="button">Add a user to plan</a>
</div>
{%endblock%}