Django pagination and "current page" - django

I'm currently developing a Django application which will make use of the infamous "pagination" technique. I'm trying to figure out how the django.core.paginator module works.
I have an application with a Question model. I will be listing all of the questions using this paginator. There will be 20 questions per page.
def show_question(question_pk):
questions = Question.objects.all()
paginator = Paginator(questions, 20)
page = ... # Somehow figure out which page the question is on
return render_to_response('show_question.html', { 'page' : page })
In the view, where I list the different pages as "... 2, 3, 4, 5, 6, ..." I want to highlight the current page somehow, like many pages do.
There are really two things I want to know:
How do I make Django figure out which page the question is located at?
How would I write my template to properly "highlight" the currently visited page?
EDIT: Sorry, I forgot part of this question. I would also like any page except for the current one to be a link to /questions/{{ that_page.start_index }}. So basically every page link would link to the first question on that page.

Hmm... I see from your comment that you don't want to do the ol' GET parameter, which is what django.core.paginator was written for using. To do what you want, I can think of no better way than to precompute the page that each question is on. As an example, your view will end up being something like:
ITEMS_PER_PAGE = 20
def show_question(question_pk):
questions = Question.objects.all()
for index, question in enumerate(questions):
question.page = ((index - 1) / ITEMS_PER_PAGE) + 1
paginator = Paginator(questions, ITEMS_PER_PAGE)
page = paginator.page(questions.get(pk=question_pk).page)
return render_to_response('show_question.html', { 'page' : page })
To highlight the current page in the template, you'd do something like
{% for i in page.paginator.page_range %}
{% ifequal i page.number %}
<!-- Do something special for this page -->
{% else %}
<!-- All the other pages -->
{% endifequal %}
{% endfor %}
As for the items, you'll have two different object_lists to work with...
page.object_list
will be the objects in the current page and
page.paginator.object_list
will be all objects, regardless of page. Each of those items will have a "page" variable that will tell you which page they're on.
That all said, what you're doing sounds unconventional. You may want to rethink, but either way, good luck.

Django, at least from version 1.2, allows us to complete this task by using pure default pagination template tags.
{% for page in article_list.paginator.page_range %}
{% if page == article_list.number %}
{{ page }}
{% else %}
{{ page }}
{% endif %}
{% endfor %}
Where article_list is instance of
paginator = Paginator(article_list, 20)
try:
article_list = paginator.page(int(page))
except (EmptyPage, InvalidPage):
article_list = paginator.page(paginator.num_pages)

django-pagination should do what you want and comes wrapped in a pretty package you can just plug-in and use. It essentially moves the code from your views to the templates and a middleware.
EDIT: I just saw your edit.
You can get the current objects on a page using {% autopaginate object_list %}, which replaces object_list with the current objects for any given page. You can iterate through it and if you want the first, you should be able to treat it like a list and do object_list[0].
If you want to keep this within your views, you could do something like this:
def show_question(question_pk):
questions = Question.objects.all()
paginator = Paginator(questions, 20)
return render_to_response('show_question.html', { 'page' : paginator })
Within your template, you can access the current page you're on by doing:
# Gives you the starting index for that page.
# For example, 5 objects, and you're on the second page.
# start_index will be 3.
page.start_index
# You can access the current page number with:
# 1-based index
page.number
With that, you should be able to do everything you need.
There are a couple good examples here.

Related

Check and clear filters with django-filter

I am using django-filter to filter a ListView and would like to display a "Clear all filters" link if any filters are applied.
Due to the generic nature of the filtering system I haven't yet found a straightforward way to achieve this.
The only thing I came up with so far is to return the regular queryset in the get_queryset method of the view if a "clear" flag is present in the request, however this doesn't actually clear the filters - it just returns all the data.
Does anyone have a solution/idea for this?
Update: Solution
After Jerin's comment I decided to solve this problem in 2 separate parts:
has filter:
I check if any of the fields I defined in my filter class are in the request. My solution looks a bit different as I'm using class based views so I abstracted it away in a mixin but if you're using simple views like here, you could just do:
def product_list(request):
f = ProductFilter(request.GET, queryset=Product.objects.all())
has_filter = any(field in request.GET for field in
set(f.get_fields()))
return render(request, 'my_app/template.html', {
'filter': f,
'has_filter': has_filter
})
clear all filters:
A simple redirect to your list view:
{% if has_filter %}
{% trans 'Clear all filters' %}
{% endif %}
Here is the mixup version of the answer (combination of mine and Chris)
You could place a Clear all filters button and that will redirect to your default ListView (/host/end/point/).
But some non-filter parameters (such as pagination or something else) may occur in URL. So the better option is, check for any filter fields in URL and if so, display the filter clearing link
The opted solution is,
def product_list(request):
f = ProductFilter(request.GET, queryset=Product.objects.all())
has_filter = any(field in request.GET for field in set(f.get_fields()))
return render(request, 'my_app/template.html', {
'filter': f,
'has_filter': has_filter
})
and in template,
{% if has_filter %}
{% trans 'Clear all filters' %}
{% endif %}
Just make a button and point to the base search field.
<a class="btn btn-warning" href="{% url 'App:FilterView' %}">Reset</a>
If your FilterSet instance is available on the template you can check for filter.is_bound like this:
{% if filter.is_bound %}
Clear filters
{% endif %}
If you are using the FilterMixin or the FilterView, your FilterSet instance will be available as filter to the template as above.
I like this simple solution, however when I attempt to use it the current filter parameters are some how getting appended to the url even though it's the base url in the anchor.
So hovering over the button my link (determined using {% url 'app:view' %} shows
localhost/app/view correctly
However when clicking the button the url in browser has the parameters appended
localhost/app/view/?filter1=val1&filter2=val2 etc.
Is django caching something? Is browser (Chrome) caching? Can I force something in the anchor to not use them?
Answered my own, but for anyone else passing by:
I had the anchor on a button within a the filter form, although it was not a submit button moving it outside the form gave the desired result.

Django functions issue and urlconf confusion

I couldn't place my question into one sentence.
I was following a tutorial to make a blog from scratch. But the tutorial predicted having all the categories, tags, months and years listings in separate templates.
I want to add a list of categories, a list of months and years on the main blog page.
So here is what I got. With this code, the list of categories is shown in the main page but only if you go to the blog/category url, and not in just blog/ where I want it to be.
**(r'^$', list),**
(r'^archive/(\d{1,2})/$', list),
(r'^\d{2}/d{4}/$', month),
(r'^([0-9]{4}/\d{1,2})/(?P<slug>.*)/$', detail),
(r'^(?P<year>\d{4})/$', year),
**(r'^category/$', category),**
I also tried:
(r'^$', category),
but no luck.
This is the same code from the template in category.html and in list.html:
{% if categories %}
{% for category in categories %}
<li class="cat-item"><a href="category/{{ category.name.lower }}/"
title="{{ category.name.capitalize }}">
{{ category.name.capitalize }}</a>
</li>
{% endfor %}
{% endif %}
Views.py:
def category(request):
return render_to_response('blog/list.html', {'categories':Category.objects.all(),},)
It was like this. I tried this, but no luck in def list:
return render_to_response('blog/list.html',{'posts':posts,
'next':next,
'previous':previous,
'categories':Category.objects.all(),
},)
How can I get what shows on blog/category to show on blog/ also?
Thanks.
When you type an url in your browser a request is sent to your server. Django then takes the url and matches it against it url patterns to determine the proper view. As soon as a view is found django stops matching and executes this view which in turn returns a response.
If you want to use your categories in different views you either have to to make sure that in every view the same categories context variable is provided to the template or, which is usually much better, write a simple custom template tag. For your categories this could look like this:
#register.inclusion_tag('blog/category_list.html')
def categories_list():
return { 'categories': Category.objects.all() }
In the file 'blog/categoy_list.html' would then be the code that is currently both in 'categories.html' and 'list.html'. In these files replace it with.
{% load your_blog_tags %}
{% categories_list %}
You can use that then wherever you need a category list. Of course the same applies for years and month lists.

loop in Django template: how to control the loop iterator?

I'm using Django to show a list of posts. Each post has a 'is_public' field, so if one post's 'is_public' equals to False, it should not be shown to the user. Also, I want to show a fixed number of posts in one page, but this number can be changing depending on views.
I decided to crop the queryset in template as a few views are using the same template, generating it in the view means a lot of repeated codes.
If written in python, it should look like this:
i=number_of_posts_to_show_in_one_page
while i:
if qs[i].is_public == True:
#show qs[i] to the page
i--
As the django template does not support while loop and for loop seems hard to control, is there a way of achieving this? Or should I do it in another way?(One idea is to crop the qs before looping)Thanks!
Update:
I've written this template tag to pre-process the queryset:
#register.simple_tag(takes_context=True)
def pre_process_list(context,list,numbers):
#if not user.has_perm('admin'):
context['result_list']=list.filter(is_public=True, is_removed=False)[0:numbers]
#else:
#context['result_list']=list[0:numbers]
return ''
Before using for loop in the template, I'll pass the queryset to this templage tag, and use a simple for loop to show its result.
If in the future I want to show non-public posts to admins(which is not decided yet), I can write in some logic like the commented ones, and have them styled differently in the template.
{% for post in posts %}
{% if post.is_public %}
{{ post }}
{% endif %}
{% endfor %}
Though this would be a perfect use case for a manager.
You could write a simple manager that filters public posts.
class PublicPostManager(models.Manager):
def get_query_set(self):
return super(PublicPostManager, self).get_query_set().filter(is_public=True)
Then you would add it to your Post Class:
class Post(models.Model):
...
public = PublicPostManager()
Then you could pass post.public.all() as public_posts to your template and simplify your loop:
{% for post in public_posts %}
{{ post }}
{% endfor %}
#arie has a good approach with the manager, but you can easily do the same without writing a manager:
# View
posts = Post.objects.filter(is_public=True) # or use the manager
# Now, you can either limit the number of posts you send
# posts = posts[:5] (only show five in the view)
return render_to_response('foo.html',{'posts':posts})
# Template
# Or you can do the limits in your template itself:
{% for post in posts|slice:":5" %}
{{ post }}
{% endfor %}
See the slice filter on more information.
However, since this is a common operation, with django 1.3 you can use class based views to automate most of this.

Paginating a Detail view in Django

I'm new to Django and for my first project I'm building a portfolio. And I need a little kick-start with pagination help. I have an "index" view with a list of projects and a detail view of each project. In the detail view, I want a feature to be able to paginate between each individual object. I've gone through the Pagination documenation and applied what I learned with my index view but when I try to do the same thing with my detail view I get a TypeError saying my "object of type 'Project' has no len().
Here's a sample of my views.py code for reference:
def index( request ):
all_projects = Project.objects.all().order_by( '-pub_date' )
paginator = Paginator( all_projects, 12 )
try:
page = int( request.GET.get( 'page','1' ))
except ValueError:
page = 1
try:
projects = paginator.page( page )
except (EmptyPage,InvalidPage):
projects = paginator.page( paginator.num_pages )
return render_to_response( 'portfolio/index.html', { 'all_projects':all_projects, 'projects':projects, 'MEDIA_URL':MEDIA_URL })
def detail( request, project_id ):
project = get_object_or_404( Project, id=project_id )
return render_to_response( 'portfolio/detail.html', { 'project':project, 'MEDIA_URL':MEDIA_URL } )
Apologies if I sound n00b-ish because I am, and gratitude in advance for any help. Also, I read this previous post but it didn't seem to apply to me because my views aren't Class-based.
Django has built-in get_next_by_FOO()/get_previous_by_FOO() methods which will return the next/previous object depeding on a datetime-field.
You could access them in the template by somethow like:
{{ project.get_next_by_pub_date.title }}
I would say that this is the preferred method over using pagination for that, as you will get a nice url you can define in your model's get_absolute_url for every item!
To paginate you need an instance of a QuerySet, not an object! So you should replace your get_object_or_404 call by a filter/all. So it would be basically the same as the list view, but just pass the number 1 to the paginator, as you already do!
I actually do not have that setup through Django's pagination. I used this code:
prev_issue = Issue.objects.filter(title=title).filter(number__lt=issue.number).order_by('-number')[:1]
next_issue = Issue.objects.filter(title=title).filter(number__gt=issue.number).order_by('number')[:1]
In your case, I would do something like this, but you would have to filter by something, too:
prev_project = Project.objects.order_by('-pub_date')[:1]
next_project = Project.objects.order_by('pub_date')[:1]
Then put the two in the context.
I also recommend django-pagination. I notice you probably want the pagination to stay on the index, correct? http://code.google.com/p/django-pagination/
You just have to mess with the template codes and it works great.
The great thing about Django is, that there is code for nearly every common programming problem, that you can download and use in your own project. (and most of the django packages are quiet well written too)
for pagination check out http://pypi.python.org/pypi/django-pagination
it's really easy to install and setup, so you do not have to think about pagination and focus on coding your software!
hope this helps, Anton
In my views.py
def ProjectDetail(request,pk):
context = {}
template = 'views/projectdetail.html'
project = ''
prev = Project.objects.filter(pk__lt=pk).order_by('-pk')[:1]
next = Project.objects.filter(pk__gt=pk).order_by('pk')[:1]
try:
print(prev[0].pk)
print(next[0].pk)
except:
pass
project = Project.objects.filter(pk=pk)
context['categories'] = ProjectCategory.objects.all()
paginator = Paginator(project, 1) # Show 25 contacts per page
page = request.GET.get('page')
try:
data = paginator.page(page)
except PageNotAnInteger:
# If page is not an integer, deliver first page.
data = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results.
data = paginator.page(paginator.num_pages)
if prev:
context['prev'] = prev[0].pk
if next:
context['next'] = next[0].pk
context['data'] = data
return render_to_response(template, context,context_instance=RequestContext(request))
in my template i have
<div class="row">
<a {% if next %} href="{% url 'task:project-detail' next %}" class="btn btn-primary pull-right" {% else %} class="btn btn-primary pull-right disabled" {% endif %}>Next</a>
<a {% if prev %} href="{% url 'task:project-detail' prev %}" class="btn btn-primary pull-left" {% else %} class="btn btn-primary pull-left disabled" {% endif %} >Previous</a>
</div>

Pagination problem

I'm using this code for my pagination, and I'd like the user's choice to be persistent throughout the site (this has been solved so far)...the only problem now is that the session variable now is permanent until the session is cleared by closing the browser. Also, how can I get the adjacent pages displayed...like in the digg-style Django paginator. I haven't been able to make sense of how to implement this into my code.
The code is as follows:
from django.core.paginator import Paginator, InvalidPage, EmptyPage
def paginate(request, object_list, paginate_by=10):
try:
if "per_page" in request.session:
per_page = request.session["per_page"]
else:
request.session["per_page"] = int(request.REQUEST['p'])
per_page = request.session["per_page"]
request.session.set_expiry(0)
except:
per_page = 10
paginator = Paginator(object_list, per_page)
try:
page = int(request.GET.get('page', '1'))
except ValueError:
page = 1
try:
items = paginator.page(page)
except (EmptyPage, InvalidPage):
items = paginator.page(paginator.num_pages)
return items
Then in my template I have this to render the pagination links:
<div class="pagination" align="center">
<span class="step-links">
{% if items.has_previous %}
previous
{% endif %}
<span class="current">
Page {{ items.number }} of {{ items.paginator.num_pages }}
</span>
{% if items.has_next %}
next
{% endif %}
</span>
</div>
You can achieve this by enabling sessions.
I recommend reading through the chapter Sessions, Users, and Registration on the djangobook website.
Edit: Now that you've enabled sessions, I think the problem is the hyperlinks in the template. Use an ampersand to separate multiple parameters in a url, for example
next
Edit 2: I'm not sure if I understand what the problem is with the session expiry. The line that sets the session to expire when the browser closes is request.session.set_expiry(0). See the django docs on Using Sessions in views if you want to change that.
To make a Digg style paginator, you need to write a function that takes the current page number and the total number of pages, and returns a list of page numbers. Then, in the template, loop through the page numbers and construct links to the pages.
A list of lists of page numbers would allow you to split the page numbers into groups, eg
[[1,2], [20,21,22,23,24], [30,31]]