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 would like to add post list from main page to another subpages. (main page to subpage called "programowanie")
For example:
I have a website wwww.example.com. On this website I have a post list that is generated from admin panel (I can add, delete a posts using admin panel).
The problem is that when I try to copy templates from start page with post list to other subpage (called: www.example.com/programowanie) it doeasn't work (I see a template from main page but without post list)
I think the problem is in templates/blog/post/list.html in loop {% for post in posts %}
If I solve this problem I would like to add in admin panel different overlap to publish posts only in "programowanie" subpage.
This is my files:
blog/views.py
from django.shortcuts import render, get_object_or_404, HttpResponse
from .models import Post, Posta, Comment
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.views.generic import ListView
from .forms import EmailPostForm, CommentForm
from django.core.mail import send_mail
from taggit.models import Tag
from django.db.models import Count
def post_share(request, post_id):
# Pobranie posta na podstawie jego identyfikatora.
post = get_object_or_404(Post, id=post_id, status='published')
sent = False
if request.method == 'POST':
# Formularz został wysłany.
form = EmailPostForm(request.POST)
if form.is_valid():
# Weryfikacja pól formularza zakończyła się powodzeniem…
cd = form.cleaned_data
post_url = request.build_absolute_uri(
post.get_absolute_url())
subject = '{} ({}) zachęca do przeczytania "{}"'.format(cd['nick'], cd['email'], post.title)
message = 'Przeczytaj post "{}" na stronie {}\n\n Komentarz dodany przez {}: {}'.format(post.title, post_url, cd['nick'], cd['komentarz'])
send_mail(subject, message, 'admin#myblog.com', [cd['adresat']])
sent = True
else:
form = EmailPostForm()
return render(request, 'blog/post/share.html', {'post': post,
'form': form,
'sent': sent})
class PostListView(ListView):
queryset = Post.published.all()
context_object_name = 'posts'
paginate_by = 3
template_name = 'blog/post/list.html'
def post_list(request, tag_slug=None):
object_list = Post.published.all()
tag = None
if tag_slug:
tag = get_object_or_404(Tag, slug=tag_slug)
object_list = object_list.filter(tags__in=[tag])
paginator = Paginator(object_list, 3) # Trzy posty na każdej stronie.
page = request.GET.get('page')
try:
posts = paginator.page(page)
except PageNotAnInteger:
# Jeżeli zmienna page nie jest liczbą całkowitą,
# wówczas pobierana jest pierwsza strona wyników.
posts = paginator.page(1)
except EmptyPage:
# Jeżeli zmienna page ma wartość większą niż numer ostatniej strony
# wyników, wtedy pobierana jest ostatnia strona wyników.
posts = paginator.page(paginator.num_pages)
return render(request,
'blog/post/list.html',
{'page': page,
'posts': posts,
'tag': tag})
def post_detail(request, year, month, day, post):
post = get_object_or_404(Post, slug=post,
status='published',
publish__year=year,
publish__month=month,
publish__day=day)
comments = post.comments.filter(active=True)
if request.method == 'POST':
comment_form = CommentForm(data=request.POST)
if comment_form.is_valid():
new_comment = comment_form.save(commit=False)
new_comment.post = post
new_comment.save()
else:
comment_form = CommentForm()
# Lista podobnych postów.
post_tags_ids = post.tags.values_list('id', flat=True)
similar_posts = Post.published.filter(tags__in=post_tags_ids)\
.exclude(id=post.id)
similar_posts = similar_posts.annotate(same_tags=Count('tags'))\
.order_by('-same_tags','-publish')[:4]
return render(request,
'blog/post/detail.html',
{'post': post,
'comments': comments,
'comment_form': comment_form,
'similar_posts': similar_posts})
def programowanie(request):
return render(request, 'blog/post/base.html')
blog/models.py
# -*- coding: utf-8 -*-
from taggit.managers import TaggableManager
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class PublishedManager(models.Manager):
def get_queryset(self):
return super(PublishedManager,
self).get_queryset()\
.filter(status='published')
class Post(models.Model):
STATUS_CHOICES = (
('draft', 'Roboczy'),
('published', 'Opublikowany'),
)
title = models.CharField(max_length=250)
slug = models.SlugField(max_length=250,
unique_for_date='publish')
author = models.ForeignKey(User,
related_name='blog_posts')
body = models.TextField()
publish = models.DateTimeField(default=timezone.now)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
status = models.CharField(max_length=10,
choices=STATUS_CHOICES,
default='draft')
objects = models.Manager() # Menedżer domyślny.
published = PublishedManager() # Menedżer niestandardowy.
tags = TaggableManager()
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:post_detail',
args=[self.publish.year,
self.publish.strftime('%m'),
self.publish.strftime('%d'),
self.slug])
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
komentarz = models.TextField()
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
active = models.BooleanField(default=True)
class Meta:
ordering = ('created',)
def __str__(self):
return 'Komentarz dodany przez {} dla posta {}'.format(self.name,
self.post)
blog/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
# Widoki posta.
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.programowanie, name='programowanie'),
#url(r'^$', views.PostListView.as_view(), name='post_list'),
url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\
r'(?P<post>[-\w]+)/$',
views.post_detail,
name='post_detail'),
url(r'^(?P<post_id>\d+)/share/$', views.post_share,
name='post_share'),
url(r'^tag/(?P<tag_slug>[-\w]+)/$', views.post_list,
name='post_list_by_tag'),
]
urls.py
from django.conf.urls import include, url
from django.contrib import admin
from blog import views
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^about/', views.about, name="about"),
url(r'^programowanie/', views.programowanie, name="programowanie"),
url(r'^algorytmy/', views.algorytmy, name="algorytmy"),
url(r'^kontakt/', views.kontakt, name="kontakt"),
url(r'', include('blog.urls',
namespace='blog',
app_name='blog')),
]
blog/templates/base.html
{% load staticfiles %}
<!DOCTYPE html>
<html>
<head>
{% include "navbar.html" with page=posts %}
<title>{% block title %}{% endblock %}</title>
<link href="{% static "admin/css/blog.css" %}" rel="stylesheet">
</head>
<body>
<div id="content">
{% block content %}
{% endblock %}
</div>
<div id="sidebar">
<h2>Mój blog</h2>
<p>To jest mój blog.</p>
</div>
</body>
</html>
blog/templates/post/list.html
{% extends "blog/base.html" %}
{% block title %}Mój blog{% endblock %}
{% block content %}
<h1>Mój blog</h1>
{% if tag %}
<h2>Posty oznaczone tagiem "{{ tag.name }}"</h2>
{% endif %}
{% for post in posts %}
<h2>
<a href="{{ post.get_absolute_url }}">
{{ post.title }}
</a>
</h2>
<p class="tags">
Tagi:
{% for tag in post.tags.all %}
<a href="{% url "blog:post_list_by_tag" tag.slug %}">
{{ tag.name }}
</a>
{% if not forloop.last %}, {% endif %}
{% endfor %}
</p>
<p class="date">
Opublikowany {{ post.publish }} przez {{ post.author }}
</p>
{{ post.body|truncatewords_html:30|linebreaks }}
{% endfor %}
{% include "pagination.html" with page=posts %}
{% endblock %}
blog/templates/post/detail.html
{% extends "blog/base.html" %}
{% block title %}{{ post.title }}{% endblock %}
{% block content %}
<h1>{{ post.title }}</h1>
<p class="date">
Opublikowany {{ post.publish }} przez {{ post.author }}
</p>
{{ post.body|linebreaks }}
<p>
<a href="{% url "blog:post_share" post.id %}">
Udostępnij posta
</a>
</p>
<h2>Podobne posty</h2>
{% for post in similar_posts %}
<p>
{{ post.title }}
</p>
{% empty %}
Nie ma podobnych postów.
{% endfor %}
{% with comments.count as total_comments %}
<h2>
{{ total_comments }} komentarz{{ total_comments|pluralize:"y" }}
</h2>
{% endwith %}
{% for comment in comments %}
<div class="comment">
<p class="info">
Komentarz {{ forloop.counter }} dodany przez {{ comment.name }}
{{ comment.created }}
</p>
{{ comment.komentarz|linebreaks }}
</div>
{% empty %}
<p>Nie ma jeszcze żadnych komentarzy.</p>
{% endfor %}
{% if new_comment %}
<h2>Twój komentarz został dodany.</h2>
{% else %}
<h2>Dodaj nowy komentarz</h2>
<form action="." method="post">
{{ comment_form.as_p }}
{% csrf_token %}
<p><input type="submit" value="Dodaj komentarz"></p>
</form>
{% endif %}
{% endblock %}
Thanks for any help !! (I thinking about this third day )
The problem you have it's in the views.
Django template has to be rendered by a view, from this view is where you get the data to be rendered in the template. It doesn't matter which url you want to use and which template you are using in the views. What this means is that you can have different urls pointing to the same template (www.example.com/blog/ or www.example.com/programming/) and both render the same template.
If i understood you right, all you have to do is change this :
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.programowanie, name='programowanie'),
To this:
url(r'^$', views.post_list, name='post_list'),
url(r'^programowanie/$', views.post_list, name='programowanie'),
You can refer to the official Django website in order to get more information about this : https://docs.djangoproject.com/en/2.0/intro/tutorial03/
Thanks for help :)
I solved this problem. There was a problem in urls.py file.
I'm currently having issues with my Django pagination. I have a query set of 9 objects and am paginating one object to a page. So I should have 9 pages total.
Paginator is showing that I have 9 pages, but when I click the "next" page button my (Always on the last/last two pages) my url turns to: http://127.0.0.1:8000/forum/1?page=7
Then I get a 404 page not found error along with "Invalid page (7): That page contains no results"
Here is my class code:
class DirectoryClass(generic.ListView):
template_name = "forum_directory.html"
model = Directory
paginate_by = 1
def get_context_data(self, **kwargs):
context = super(DirectoryClass, self).get_context_data(**kwargs)
directory = Directory.objects.filter(pk=self.kwargs['directory_id'])
context['page'] = 'forum'
context['name'] = directory.first().name
context['user'] = self.request.user
topic_set = directory.first().topic_set.all().order_by('-last_post')
print(topic_set.all())
paginator = Paginator(topic_set, self.paginate_by)
page = self.request.GET.get('page')
try:
topic_set = paginator.page(page)
except PageNotAnInteger:
topic_set = paginator.page(1)
except EmptyPage:
topic_set = paginator.page(paginator.num_pages)
context['topics'] = topic_set
context['page'] = page
return context
Here is the HTML used to change the page:
<div style="width: 1240px; margin: auto; text-align: right;">
{% if topics.has_other_pages %}
<ul class="pagination forum-pagination">
{% if topics.has_previous %}
<li>«</li>
{% else %}
<li class="disabled"><span>«</span></li>
{% endif %}
{% for i in topics.paginator.page_range %}
{% if topics.number == i %}
<li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li>
{% else %}
<li>{{ i }}</li>
{% endif %}
{% endfor %}
{% if topics.has_next %}
<li>»</li>
{% else %}
<li class="disabled"><span>»</span></li>
{% endif %}
</ul>
{% endif %}
</div>
Here is the url
path(r'/<int:directory_id>',views.DirectoryClass.as_view(), name='forum_directory'),
What am I doing wrong here?
def get_context_data(self, **kwargs):
context = super(DirectoryClass, self).get_context_data(**kwargs)
context['page'] = 'forum'
context['user'] = self.request.user
return context
def get_queryset(self):
directory = Directory.objects.filter(pk=self.kwargs['directory_id'])
topics = directory.first().topic_set.all().order_by('-last_post')
return topics
use this only in your ListView, as Django provides pagination to all the Class Based View
Wagtail Blog Site - Comment Model Form Issues
I'm creating a blog site, using Wagtail, and I've run in to a snag. I've added a Comment Model to my page, which I can add comments through the admin section and they display on the correct posts, but the comment form I've created is not displaying for some reason. Here's my relevant code. Any tips on where I went wrong would be greatly appreciated.
blog/models.py
class BlogPage(Page):
date = models.DateField("Post date")
intro = models.CharField(max_length=250)
body = RichTextField(blank=True)
#tag manager
tags = ClusterTaggableManager(through=BlogPageTag, blank=True)
#get feature image
def main_image(self):
gallery_item = self.gallery_images.first()
if gallery_item:
return gallery_item.image
else:
return None
search_fields = Page.search_fields + [
index.SearchField('intro'),
index.SearchField('body'),
]
content_panels = Page.content_panels + [
MultiFieldPanel([
FieldPanel('date'),
FieldPanel('tags'),
], heading="Blog information"),
FieldPanel('intro'),
FieldPanel('body'),
InlinePanel('gallery_images', label="Gallery images"),
]
def serve(self, request):
# Get current page
post = self
# Get comment form
form = CommentForm(request.POST or None)
# Check for valid form
if form.is_valid():
comment = form.save(commit=False)
comment.post = post
comment.save()
return redirect(request.path)
return render_to_response(self,
{
'post': post,
'form': form,
},
context_instance=RequestContext(request))
class Comment(models.Model):
post = models.ForeignKey(BlogPage, related_name='comments')
author = models.CharField(max_length=250)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
def approve(self):
self.approved_comment = True
self.save()
def __unicode__(self):
return self.text
def __str__(self):
return self.text
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ('author', 'text',)
blog_page.html
{% extends "base.html" %}
{% load wagtailcore_tags wagtailimages_tags %}
{% block body_class %}template-blogpage{% endblock %}
{% block content %}
<div class="section">
<div class="container">
<h1 class="title">{{ page.title }}</h1>
<p class="meta subtitle">{{ page.date }}</p>
{% with page.main_image as main_image %}
{% if main_image %}{% image main_image fill-500x300 %}{% endif %}
{% endwith %}
<p>{{ main_image.caption }}</p>
<div class="hero-body subtitle">{{ page.intro }}</div>
<div class="content">
{{ page.body|richtext }}
{% if page.tags.all.count %}
<div class="tags">
<h3>Tags</h3>
{% for tag in page.tags.all %}
<span class="tag is-primary is-medium is-link"><a style="color: white" href="{% slugurl 'tags' %}?tag={{ tag }}">{{ tag }}</a></span>
{% endfor %}
</div>
{% endif %}
<p>Return to blog archive</p>
<hr>
<br>
<form action="" method="POST">
{% csrf_token %}
<table>
{{ form.as_table }}
</table>
<input class="control button is-primary" type='submit' name='submit' value='Add Comment'>
</form>
<br>
<hr>
<div class="section">
{% if page.comments.all.count %}
<h2 class='subtitle'>Comments</h2>
<div class="comments">
{% for comment in page.comments.all %}
{% if comment.approved_comment %}
<div class="comment">
<h5 class="date">{{ comment.created_date }}</h5>
<strong><h3 class="title is-3">{{ comment.author }}</h3></strong>
<h4 class="subtitle is-5">{{ comment.text|linebreaks }}</h4>
<br>
<hr>
</div>
{% endif %}
{% empty %}
<br>
<p>No comments yet...</p>
{% endfor %}
</div>
{% endif %}
</div>
</div>
</div>
</div>
{% endblock %}
Now I'm getting an error saying:
File "/home/kenneth/development/web/sites/mysite/dynamicsalesops/blog/models.py", line 88, in serve
context_instance=RequestContext(request))
TypeError: render_to_response() got an unexpected keyword argument 'context_instance'
Your view_post function is never used. In Wagtail, rendering pages as HTML is handled by a serve method on the page model itself, not by a separate view function: http://docs.wagtail.io/en/v1.9/reference/pages/theory.html#anatomy-of-a-wagtail-request
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.