I am at the beginner level in the Django Framework. The queryset works well in my post list. But I face a problem in pagination to the second page queryset according to the tag field in my blog post list. When I go to the second page it shows the main list of the second page, not queryset page. I don't know where the problem behind the seen...
models.py code
class Post(models.Model):
TOPICS = (
('Programming' , 'Programming'),
('C' , 'C'),
('C++' , 'C++'),
('Java' , 'Java'),
('Python' , 'Python'),
)
title = models.CharField(max_length=100, blank=False, null=False)
content = models.TextField()
tag = models.CharField(max_length=50, choices=TOPICS, blank=False, null=False, default='Programming')
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return self.title
#redirect to post_detail when some post a blog
def get_absolute_url(self):
return reverse('post_detail', kwargs={'pk':self.pk})
viwes.py code
from django.core.paginator import Paginator
from .filters import BlogFilter
def home(request):
posts = Post.objects.all().order_by('-date_posted')
postFilter = BlogFilter(request.GET, queryset=posts)
posts = postFilter.qs
paginator = Paginator(posts, 3)
page_number = request.GET.get('page')
page_obj = paginator.get_page(page_number)
context = {
'page_obj' : page_obj,
'postFilter' : postFilter,
}
return render(request, 'blog/index.html', context)
template code
{% extends 'blog/base.html'%}
{% load crispy_forms_tags %}
{% load static %}
{% block content %}
<section id="article">
<div class="container">
<div class="row mt-4">
<div class="col-md-8 m-auto">
<form method="get">
{{postFilter.form|crispy}}
<button class="btn btn-primary" type="submit">Search</button>
</form>
{% for i in page_obj %}
<article class="media content-section">
<a href="{% url 'user_posts' i.author.username %}">
<img class="rounded-circle article-img" src="{{i.author.profile.image.url}}" alt="">
</a>
<div class="media-body">
<div class="article-metadata">
<a class="mr-2" href="{% url 'user_posts' i.author.username %}">{{ i.author }}</a>
<small class="text-muted">{{i.date_posted|date:"F d, Y"}}</small>
</div>
<h2><a class="article-title" href="{% url 'post_detail' i.id %}">{{i.title}}</a></h2>
<p class="article-content">{{i.content|linebreaks|truncatewords:50}}</p>
</div>
</article>
{% endfor %}
{% 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 %}
</div>
</div>
</div>
</section>
{% endblock %}
Related
I'm applying pagination on my sports.html page. In views.py I'm using ListView and using paginate_by = 2 but issue is pagination is not taking effect on webpage.
Pagination numbers are visible on page and when clicking on those page numbers it's not showing any error but all posts are visible on all pages, posts are not divided by paginate_by value.
Can anyone point out what I'm doing wrong here ?
views.py
class SportsList(ListView):
model = Sports
template_name = 'frontend/sports.html'
paginate_by = 2
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['main'] = Main.objects.all()
context['sports'] = Sports.objects.all()
return context
sports.html
<section class="blog_area">
<div class="container">
<div class="row">
<div class="col-lg-8">
<div class="blog_left_sidebar">
{% for sport in sports %}
<article class="row blog_item">
<div class="col-md-3">
<div class="blog_info text-right">
<ul class="blog_meta list">
<li>XAR<i class="lnr lnr-user"></i></li>
<li>From: {{ sport.from_date }}<i class="lnr lnr-calendar-full"></i></li>
<li>To: {{ sport.to_date }}<i class="lnr lnr-calendar-full"></i></li>
<li>{{ sport.category }}<i class="lnr lnr-layers"></i></li>
</ul>
</div>
</div>
<div class="col-md-9">
<div class="blog_post">
<img src="{{ sport.featured_image.url }}" alt="">
<div class="blog_details">
<a href="{% url 'sports_details' sport.slug %}">
<h2>{{ sport.title }}</h2>
</a>
<p>{{ sport.content|truncatewords:30|safe }}</p>
View More
</div>
</div>
</div>
</article>
{% endfor %}
{% if is_paginated %}
<nav class="blog-pagination justify-content-center d-flex">
<ul class="pagination">
{% if page_obj.has_previous %}
<li class="page-item">
<a href="?page={{ page_obj.previous_page_number }}" class="page-link">
<span aria-hidden="true">
<span class="lnr lnr-chevron-left"></span>
</span>
</a>
</li>
{% endif %}
{% for num in page_obj.paginator.page_range %}
{% if page_obj.number == num %}
<li class="page-item active">{{ num }}</li>
{% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
<li class="page-item">{{ num }}</li>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<li class="page-item">
<a href="?page={{ page_obj.next_page_number }}" class="page-link" aria-label="Next">
<span aria-hidden="true">
<span class="lnr lnr-chevron-right"></span>
</span>
</a>
</li>
{% endif %}
</ul>
{% endif %}
</nav>
</div>
</div>
</div>
</div>
</section>
This is because you are creating your queryset on get_context_data. You are not respecting the listview structure. Try something like this on your view:
class SportsList(ListView):
queryset = Sport.objects.all()
context_object_name = “sports”
template_name = 'frontend/sports.html'
paginate_by = 2
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['main'] = Main.objects.all()
return context
You need to use the following in the views.py.
context_object_name = 'sports'
By default, While a Django view is executing, self.object_list will contain the list of objects (usually, but not necessarily a queryset) that the view is operating upon. You can see the reference in Django doc here.
generic list view
Of course, you are adding 'sports' in the context of def get_context_data but a Django generic list view need to get operated upon the value mentioned in context_object_name or the object_list.
Hence in your views.py use:
class SportsList(ListView):
model = Sports
template_name = 'frontend/sports.html'
paginate_by = 2
context_object_name = 'sports'
ordering = ["id"]
I am having a problem in categorize Posts. I have categories in Post Model, Please help me solve this issue!
MODELS.PY
html= "html"
css= "css"
python= "python"
javascript = "javascript"
Lang=(
(html,"HTML"),
(css,"CSS"),
(python,"PYTHON"),
(javascript,"JAVASCRIPT")
)
Broilerplate = "Broilerplate"
Simple_Tags = "Simple Tags"
Elements = "Elements"
Webpages = "Webpages"
Category = (
(Broilerplate,"BROILERPLATE"),
(Simple_Tags,"Simple tags"),
(Elements,"Elements"),
(Webpages,"Webpages")
)
class Post(models.Model):
title = models.CharField(max_length=75)
subtitle = models.CharField(max_length=150)
language_1 = models.CharField(max_length=100, choices=Lang, default=html)
content_1= models.TextField(blank=True)
language_2 = models.CharField(max_length=100, choices=Lang,blank=True)
content_2= models.TextField(blank=True)
language_3 = models.CharField(max_length=100, choices=Lang,blank=True)
content_3= models.TextField(blank=True)
language_4 = models.CharField(max_length=100, choices=Lang,blank=True)
content_4= models.TextField(blank=True)
language_5 = models.CharField(max_length=100, choices=Lang,blank=True)
content_5= models.TextField(blank=True)
category= models.CharField(max_length=100, choices=Category, default=Broilerplate)
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User,on_delete=models.CASCADE)
def __str__(self):
return self.title
# def update(self):
# updated_at = timezone.now()
# self.save(updated_at)
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk':self.pk})
VIEWS.PY
def search_by_category(request, category):
if request.post.objects.filter(pk=request.post.id).first().category == 'Broilerplate':
nor = request.post.objects.filter(pk=request.post.id).first().category
print(nor)
posts = Post.objects.filter(category='Broilerplate')
category = posts.first().category
print(category)
context = {'posts': posts, 'title': category , 'category': category}
return render(request, 'category.html', context)
else:
context = {'title': category , 'category': category}
return render(request, 'category.html', context)
URLS.PY
urlpatterns = [
path('html/',PostListView.as_view(), name='CodeWriter_Homepage'),
path('python/',views.CodeWriter_homepage_python, name='CodeWriter_Homepage_python'),
path('search/', views.search, name='search'),
path('categroize-by/<str:category>/', views.search_by_category, name='search_by_category'),
path('post-details/<int:pk>/',PostDetailView.as_view(), name='Post_details_page'),
path('post-update/<int:pk>/',PostUpdateView.as_view(), name='Post_update_page'),
path('post-delete/<int:pk>/',PostDeleteView.as_view(), name='Post_delete_page'),
path('user/<str:username>/', UserPostListView.as_view(), name='user-post'),
path('new-post/',PostCreateView.as_view(), name='New-post_page')
]
CATEGORY.html
How can I get the data of the post category in views.py?That will help me very much!
{% block main_post_body %}
<main class="post-body normal" >
<p class="post-heading"> Post for <b>{{ category }}</b> :</p>
{% comment %} <h1 class="mb-3">Search results for <b>{{category}}</b>: </h1> {% endcomment %}
{% comment %} {% if posts|length < 1 %}
<h3>No search results found</h3>
<p>Your search results for <b>{{ query }}</b> is not found.</p>
{% endif %} {% endcomment %}
{% for post in posts %}
<div class="row">
<div class="col span-8-of-12 card">
<div class="row">
<!-- <div class="triangle"></div>
<div class="person-info-card">
<div class="row">
<div class="col"><img src="{% static 'resoures/css/img/Me.jpg' %}" alt=""></div>
<div class="col">
<p>Ketan Vishwakarma</p>
<p class="post-no">126 Posts | 1k Followers</p>
</div>
</div>
</div> -->
<div class="col span-1-of-12">
<div class="person-img" id="person-info-card-toggle">
<img src="{{ post.author.profile.image.url }}" alt="" />
</div>
</div>
<div class="col span-7-of-12">
<h3>{{ post.title }} </h3>
<h4>{{ post.subtitle }}</h4>
</div>
<div class="col span-1-of-12">
<span class="ion-md-heart-empty"></span>
</div>
<div class="col span-1-of-12">
<span class="ion-md-add-circle-outline"></span>
</div>
<div class="col span-1-of-12 share">
<span class="ion-md-share"></span>
<ul class="dropdown-list-share">
<li><span class="ion-md-copy"> Copy</span></li>
<li><span class="ion-logo-whatsapp"> Share on Whatsapp</span></li>
<li><span class="ion-logo-facebook"> Share on facebook</span></li>
<li><span class="ion-md-more"> More</span></li>
</ul>
</div>
<div class="col span-1-of-12">
<span class="ion-md-menu"></span>
<ul class="dropdown-list">
<li>Doesn't work</li>
<li>Report</li>
<li>Report</li>
</ul>
</div>
</div>
<div class="tabs">
<ul class="tabs-list">
<li class="active">{{ post.language_1 }}</li>
{% if post.content_2 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_2 }}</li>
{% endif %}
{% if post.content_3 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_3 }}</li>
{% endif %}
{% if post.content_4 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_4 }}</li>
{% endif %}
{% if post.content_5 == "" %}
{% else %}
<li class="not-clickable hint--info" aria-label="To view this click Read more">{{ post.language_5 }}</li>
{% endif %}
<ul class="categories">
<abbr title="Categiores">
<a href="">
<span class="ion-md-code-working"></span>
{{ post.category }}
</a>
</abbr>
<!-- <li>Broilerplate</li> -->
</ul>
</ul>
<div id="tab1" class="tab active">
<p>
<pre><code class="language-{{ post.language_1 }}">
{{ post.content_1 }}
</code></pre>
</p>
</div>
<div id="tab2" class="tab">
<p>
<pre><code class="language-{{ post.language_2 }}">
{{ post.content_2 }}
</code></pre>
</p>
</div>
<div id="tab3" class="tab">
<p>
<pre><code class="language-{{ post.language_3 }}">
{{ post.content_3 }}
</code></pre>
</p>
</div>
<div id="tab4" class="tab">
<p>
<pre><code class="language-{{ post.language_4 }}">
{{ post.content_4 }}
</code></pre>
</p>
</div>
<div id="tab5" class="tab">
<p>
<pre><code class="language-{{ post.language_5 }}">
{{ post.content_5 }}
</code></pre>
</p>
</div>
</div>
<span class="ion-md-arrow-round-down"> Read More</span>
<h6>{{ post.date_posted|date:"F d, Y" }}</h6>
</div>
<div class="col span-4-of-12 main-card ">
<div class="card-small">
<h1>Result: </h1>
<div class="result-box">
<iframe src="" frameborder="0">just for fun</iframe>
</div>
<h6>{{ post.date_posted|date:"F d, Y" }}</</h6>
</div>
</div>
</div>
{% endfor %}
</main>
{% 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 main_post_body %}
NoteI have registered the Post model in admin.py
Tell me the solution to this problem I cannot get the solution I have been trying it for so long and am stuck on this.
I am trying to create a edit form to update the database using Django model Forms but the problem is that edit form part of the sizeProductMap.html page is not rendering when edit form (sizeProductMap_edit) request is made.
My models are as shown below.
models.py
class Product(models.Model):
prod_ID = models.AutoField("Product ID", primary_key=True)
prod_Name = models.CharField("Product Name", max_length=30, null=False)
prod_Desc = models.CharField("Product Description", max_length=2000, null=False)
prod_Price = models.IntegerField("Product Price/Piece", default=0.00)
prod_img = models.ImageField("Product Image", null=True)
def __str__(self):
return "{}-->{}".format(self.prod_ID,
self.prod_Name)
class Size(models.Model):
size_id = models.AutoField("Size ID", primary_key=True, auto_created=True)
prod_size = models.CharField("Product Size", max_length=20, null=False)
def __str__(self):
return "{size_id}-->{prod_size}".format(size_id=self.size_id,
prod_size=self.prod_size)
class SizeProductMapping(models.Model):
size_p_map_id = models.AutoField("Size & Product Map ID", primary_key=True, auto_created=True)
size_id = models.ForeignKey(Size, null=False, on_delete=models.CASCADE, verbose_name="Size ID")
prod_id = models.ForeignKey(Product, null=False, on_delete=models.CASCADE, verbose_name="Product Id")
def __str__(self):
return ".`. {}_____{}".format(self.size_id,
self.prod_id)
This is the form I used to add and edit the model.
forms.py
from django import forms
from user.models import SizeProductMapping
class SizeProductMapForm(forms.ModelForm):
class Meta:
model = SizeProductMapping
fields = ['size_id', 'prod_id']
Here is the view I created to add ,update and delete the record.
views.py
def sizeProductMap(request):
form = SizeProductMapForm(request.POST, request.FILES)
if request.method == 'POST':
if form.is_valid():
form.save()
return redirect("/admin1/sizeProductMap/")
else:
sizeProductMap_show = SizeProductMapping.objects.all()
# start paginator logic
paginator = Paginator(sizeProductMap_show, 3)
page = request.GET.get('page')
try:
sizeProductMap_show = paginator.page(page)
except PageNotAnInteger:
sizeProductMap_show = paginator.page(1)
except EmptyPage:
sizeProductMap_show = paginator.page(paginator.num_pages)
# end paginator logic
return render(request, 'admin1/sizeProductMap.html', {'sizeProductMap_show': sizeProductMap_show, 'form': form})
def sizeProductMap_delete(request, id):
sizeProductMap_delete = SizeProductMapping.objects.filter(size_p_map_id=id)
sizeProductMap_delete.delete()
return redirect('/admin1/productSizeMap')
def sizeProductMap_edit(request, id):
instance = SizeProductMapping.objects.get(size_p_map_id=id)
form = SizeProductMapForm(instance=instance)
if request.method == 'POST':
form = SizeProductMapForm(request.POST, instance=instance)
if form.is_valid():
form.save()
return redirect('/admin1/sizeProductMap')
return render(request, 'admin1/sizeProductMap.html', {'form': form})
This is my urls.
urls.py
from django.urls import path
from admin1 import views
urlpatterns = [
path('sizeProductMap/', views.sizeProductMap, name="admin-size-product-map"),
path('sizeProductMap_delete/<int:id>', views.sizeProductMap_delete, name="admin-size-product-map-delete"),
path('sizeProductMap_edit/<int:id>', views.sizeProductMap_edit, name="admin-size-product-map-edit"),
]
This is the Html page where I want to display the form according to the page request.
sizeProductMap.html
{% extends 'admin1/layout/master.html' %}
{% block title %}Size Product Map{% endblock %}
{% block main %}
<h1>
<center>Size Product Map</center>
</h1>
<div class="container">
<div class="row">
<div class="col-lg-2"></div>
<div class="col-lg-10">
{% if sizeProductMap_show %}
<button type="button" class="btn btn-primary mt-2" data-toggle="modal" data-target="#modal-primary">Add
Size Product Mapping
</button>
<div class="modal fade" id="modal-primary">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Size Product Mapping</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
</div>
<div class="modal-body mt-2">
<form action="{% url 'admin-size-product-map'%}" method="POST"
enctype="multipart/form-data">
{% csrf_token %}
<table border="1" class="table table-bordered border border-info">
<tr>
<th>
{{form.size_id.label_tag}}
</th>
<td>{{form.size_id}}</td>
</tr>
<tr>
<th>
{{form.prod_id.label_tag}}
</th>
<td>
{{form.prod_id}}
</td>
</tr>
</table>
<input type="Submit" name="Submit" value="Submit" class="btn btn-success w-50"><br>
<div class="modal-footer justify-content-between">
<button type="button" class="btn btn-outline-light" data-dismiss="modal">Close
</button>
</div>
</form>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</div>
<!-- /.modal -->
<div class="container-fluid ">
<div class="row">
<div class="card mt-2 border border-secondary">
<div class="card-header">
<h3 class="card-title ">Size Product Map Table</h3>
</div>
<!-- /.card-header -->
<div class="card-body">
<table class="table table-bordered border border-info">
<thead>
<tr>
<th>Size Product Mapping Id</th>
<th>Product ID</th>
<th>Size ID</th>
<th>Action</th>
</tr>
</thead>
<tbody class="justify-content-center">
{% for x in sizeProductMap_show %}
<tr>
<td>{{x.size_p_map_id}}</td>
<td>{{x.prod_id}}</td>
<td>{{x.size_id}}</td>
<td><a href="{% url 'admin-size-product-map-edit' x.size_p_map_id %}"
class="btn btn-outline-primary mt-2"><i
class="fa fa-pencil-square-o" aria-hidden="true"></i></a>
<a href="{% url 'admin-size-product-map-delete' x.size_p_map_id %}"
class="btn btn-outline-danger mt-2"><i
class="fa fa-trash" aria-hidden="true"></i></a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
<!-- /.card-body -->
<div class="card-footer clearfix ">
<ul class="pagination pagination-sm m-0 justify-content-center">
{% if sizeProductMap_show.has_previous %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.previous_page_number}}">
Previous </a>
</li>
{% endif%}
{% for x in sizeProductMap_show.paginator.page_range %}
{% if sizeProductMap_show.number == x %}
<li class="page-item active"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% else%}
<li class="page-item"><a class="page-link" href="?page={{x}}">{{x}}</a></li>
{% endif %}
{% endfor %}
{% if sizeProductMap_show.has_next %}
<li class="page-item"><a class="page-link"
href="?page={{sizeProductMap_show.next_page_number}}">
Next </a>
</li>
{% endif %}
</ul>
</div>
</div>
<!-- /.card -->
</div>
</div>
{% endif %}
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
</div>
</div>
</div>
{% endblock %}
And if it is possible to reduce the number of line of code please also help. Thanks in advance.
I've found out the answer. There was a really a silly mistake by me.
In the sizeProductMap.html there is a mistake let me point out that:
sizeProductMap.html
{% if sizeProductMap_edit %}
<form action="{% url 'admin-size-product-map-edit' x.size_p_map_id %}" method="POST">
{% csrf_token %}
{{form.size_id}}
{{form.prod_id}}
</form>
{% endif %}
Here I am checking for instance {% if sizeProductMap_edit %} this is the wrong thing.
I have to check {% if instance %} according to my views.py.
Hi I'm trying to develop an online store website using Django and I don't know why, but my price counter is not working. It was working all fine before I added some pagination, and now it's not adding all the values.Can anyone please help me out?
My views.py:
def cart(request):
cart = Cart.objects.all()[0]
context = {"cart":cart}
template = 'shopping_cart/cart.html'
return render(request, template, context)
def add_to_cart(request, slug):
cart = Cart.objects.all()[0]
try:
product = Product.objects.get(slug=slug)
except Product.DoesNotExist:
pass
except:
pass
if not product in cart.products.all():
cart.products.add(product)
messages.success(request, mark_safe("Product added to cart. Go to <a href='cart/'>cart</a>"))
return redirect('myshop-home')
else:
cart.products.remove(product)
messages.success(request, mark_safe("Product removed from cart"))
new_total = 0.00
for item in cart.products.all():
new_total += float(item.price)
cart.total = new_total
cart.save()
return HttpResponseRedirect(reverse('cart'))
My index.html(where I added pagination):
{% extends 'base.html' %}
{% block content %}
<h1>Products</h1>
<div class="container-md">
<div class="row">
{% for product in products %}
<div class="col">
<div class="card-deck" style="width: 18rem;">
<img src="{{ product.image_url }}" class="card-img-top" alt="...">
<div class="card-body">
<a class="card-title text-dark" href="{% url 'detail-view' product.slug %}">{{ product.name }}</a>
<p class="card-text">${{ product.price }}</p>
{% if not product.cart_set.exists %}
Add to Cart
{% else %}
Remove from Cart
{% endif %}
</div>
</div>
</div>
{% endfor %}
</div>
</div>
<div>
<ul class="pagination justify-content-center">
{% if is_paginated %}
{% if page_obj.has_previous %}
<a class="btn btn-outline-dark mb-4" href="?page=1">First</a>
<a class="btn btn-outline-dark 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-dark 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-dark mb-4" href="?page={{ num }}">{{ num }}</a>
{% endif %}
{% endfor %}
{% if page_obj.has_next %}
<a class="btn btn-outline-dark mb-4" href="?page={{ page_obj.next_page_number }}">Next</a>
<a class="btn btn-outline-dark mb-4" href="?page={{ page_obj.paginator.num_pages }}">Last</a>
{% endif %}
{% endif %}
</ul>
</div>
{% endblock %}
My homeview:
class homeview(ListView):
model = Product
paginate_by = 6
context_object_name = 'products'
template_name = 'index.html'
My urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('cart/', sc_views.cart, name='cart'),
path('cart/<str:slug>/', sc_views.add_to_cart, name='add-to-cart'),
path('', include('products.urls'))
]
I must get post if my category == academic (SelectField choice). But it doesn't work (posts are not shown). How can I get post data or form data for this?
I've tried
#categories.route("/category/academic")
def academic():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(
Post.date_posted.desc()).filter(
Post.category == "Academic").paginate(page=page, per_page=5)
return render_template('academic.html', posts=posts)
and
#categories.route("/category/academic")
def academic():
form = PostForm()
page = request.args.get('page', 1, type=int)
post = Post(title=form.title.data,
content=form.content.data,
category=form.category.data)
posts = Post.query.order_by(
Post.date_posted.desc()).order_by(
post.category == "Academic").paginate(page=page, per_page=5)
return render_template('academic.html', posts=posts)
and
#categories.route("/category/academic")
def academic():
page = request.args.get('page', 1, type=int)
posts = Post.query.order_by(
Post.date_posted.desc()).filter(
**PostForm**.category == "Academic").paginate(page=page, per_page=5)
return render_template('academic.html', posts=posts)
Post.category
class Post(db.Model):
id = db.Column(db.Integer, primary_key=True)
title = db.Column(db.String(100), nullable=False)
date_posted = db.Column(db.DateTime, nullable=False,
default=datetime.utcnow)
content = db.Column(db.Text, nullable=False)
category = db.Column(db.String(50))
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
PostForm.category
class PostForm(FlaskForm):
title = StringField('Title', validators=[DataRequired()])
content = TextAreaField('Content', validators=[DataRequired()])
category = SelectField('Category', validators=[DataRequired()], choices=[(
'Academic', 'Academic'), ('Art', 'Art')])
submit = SubmitField('Post')
Template (category.html)## This template for posts - Showing the category.html - All of template
{% extends "layout.html" %} {% block content %} {% for post in posts.items %}
<article class="media content-section">
<img
class="rounded-circle article-img"
src="{{ url_for('static', filename='profile_pics/' + post.author.image_file) }}"
/>
<div class="media-body">
<div class="article-metadata">
<a
class="mr-2"
href="{{ url_for('users.user_posts', username=post.author.username) }}"
>{{ post.author.username }}</a
>
<small class="text-muted">{{
post.date_posted.strftime("%Y-%m-%d")
}}</small>
<small class="article-category">
<mark
><a
class="mr-2"
href="{{ url_for('categories.category_route', category=post.category) }}"
>{{ post.category }}</a
></mark
>
</small>
</div>
<h2>
<a
class="article-title"
href="{{ url_for('posts.post', post_id=post.id) }}"
>{{ post.title }}</a
>
</h2>
<p class="article-content">{{ post.content }}</p>
</div>
</article>
{% endfor %} {% for page_num in posts.iter_pages(left_edge=1, right_edge=1,
left_current=1, right_current=2) %} {% if page_num %} {% if posts.page ==
page_num %}
<a class="btn btn-info mb-4" href="{{ url_for('main.home', page=page_num) }}">{{
page_num
}}</a>
{% else %}
<a
class="btn btn-outline-info mb-4"
href="{{ url_for('main.home', page=page_num) }}"
>{{ page_num }}</a
>
{% endif %} {% else %} ... {% endif %} {% endfor %} {% endblock content %}
Doesn't work because posts are not shown.
Well this works fine here. I copied your model, and parts of your template, which I further simplified for testing purposes. It works all just fine and results in your browser adapt nicely to the nr of items per page. In example below it is set on 2, but it works with 5 as well. Bear in mind you can only use attributes that are covered in the model and your query. Currently you have multiple issues on that. I suspect that your template is causing that you don't see any results.
python code:
page = request.args.get('page', 1, type = int)
posts = Post.query.filter_by(category = 'Academic').paginate(page=page, per_page=2)
Template:
{% extends "layout.html" %}
{% block content %}
{% for post in posts.items %}
<a href="" > {{ post.title }} </a>
{{ post.category }}
<p> {{ post.content }} </p>
{% endfor %}
{% for page_num in posts.iter_pages(left_edge=1, right_edge=1, left_current=1, right_current=2) %}
{% if page_num %}
{% if posts.page == page_num %}
<a class="btn btn-info mb-4" href="{{ url_for('home.home', page = page_num) }}">{{ page_num }}</a>
{% else %}
<a class="btn btn-outline-info mb-4" href="{{ url_for('home.home', page = page_num) }}"> {{ page_num }} </a>
{% endif %}
{% endif %}
{% endfor %}
{% endblock content %}