views:

2230

answers:

2

I'm trying to do pagination with the page parameter in the URL (instead of the GET parameter). I also want my pagination to be shared code across multiple different templates.

Given that, I think I need to do something like this :

urls.py:

url(r'^alias/page;(?P<page>[0-9]+)/(?P<id>.*)$', alias.get, name="alias"),

tempaltes/alias.html:

<div>...stuff...</div>
{% include "paginator.html" %}

templates/paginator.html :

{% if page_obj.has_previous or page_obj.has_next %}
{% load filters %}
<div class="pagination clear">
    {% if page_obj.has_previous %}
        <a href="{% url somemagic %}" class="prev">&lsaquo;&lsaquo; previous</a>
...

What is somemagic?

Assume I want to keep my url the same except set the page page_obj.previous_page_number

A: 

It will be something like the following. Except I don't know what you mean by id so I just put a generic object id. The syntax for url is {% url view_name param1 param2 ... %}

{% url alias page_obj.previous_page_number object.id %}

Updated base on your need:

{% url alias page_obj.previous_page_number object.id as prev_url %}
{% include "paginator.html" %}
...
{% if page_obj.has_previous %}
        <a href="{{prev_url}}" class="prev">&lsaquo;&lsaquo; previous</a>
Jason Christa
But pagination.html will be included from many other files for many other urls (with different template names). So I can't just put "alias" in there.
Paul Tarjan
A: 

Edit:

You need somemagic to be a variable with the name of the current view.

Try this:

{% with request.path_info|resolve_url_name as current_view %}
    {% url current_view page_obj.previous_page_number object.id %}
{% endwith %}

You can get this working with some code from django-snippets:

  1. Variable resolving URL template tag Makes the {% url %} tag resolve variables from context.
  2. Resolve URLs to view name The function resolve_to_name(path) returns the view name for path. You just need to create a filter that uses this function.

This solution wont work with urls like:

'alias/param1_regexp/param2_regexp/page;(?P<page>[0-9]+)/(?P<id>.*)$'

because you've no clue about param1 and param2.

A modification can be done to the django-snippets above to make this kind of urls work:

First snippet modifications:

from django.template import defaulttags, VariableDoesNotExist, Variable

class ResolvingURLNode(defaulttags.URLNode):
    def render(self, context):
        original_view_name = self.view_name
        try:
            resolved = Variable(self.view_name).resolve(context)
            if len(resolved) > 1:                
                self.view_name = resolved[0]
                if resolved[1]:
                    self.args = [Variable(arg) for arg in resolved[1]]
            elif len(resolved) > 0:
                self.view_name = resolved[0]
            else:
                self.view_name = resolved

        except VariableDoesNotExist:
            pass
        ret = super(defaulttags.URLNode, self).render(context)
        # restore view_name in case this node is reused (e.g in a loop) in
        # which case the variable might resolve to something else in the next iteration)
        self.view_name = original_view_name
        return ret

defaulttags.URLNode = ResolvingURLNode

Second snippet modifications

from django.core.urlresolvers import RegexURLResolver, RegexURLPattern, Resolver404, get_resolver

__all__ = ('resolve_to_name',)

def _pattern_resolve_to_name(self, path):
    match = self.regex.search(path)
    if match:
        name = ""
        if self.name:
            name = self.name
        elif hasattr(self, '_callback_str'):
            name = self._callback_str
        else:
            name = "%s.%s" % (self.callback.__module__, self.callback.func_name)
        if len(match.groups()) > 0:
            groups = match.groups()
        else:
            groups = None
        return name, groups


def _resolver_resolve_to_name(self, path):
    tried = []
    match = self.regex.search(path)
    if match:
        new_path = path[match.end():]
        for pattern in self.url_patterns:
            try:
                resolved = pattern.resolve_to_name(new_path)
                if resolved:
                    name, groups = resolved
                else:
                    name = None
            except Resolver404, e:
                tried.extend([(pattern.regex.pattern + '   ' + t) for t in e.args[0 ['tried']])
            else:
                if name:
                    return name, groups
                tried.append(pattern.regex.pattern)
        raise Resolver404, {'tried': tried, 'path': new_path}


# here goes monkeypatching
RegexURLPattern.resolve_to_name = _pattern_resolve_to_name
RegexURLResolver.resolve_to_name = _resolver_resolve_to_name


def resolve_to_name(path, urlconf=None):
    return get_resolver(urlconf).resolve_to_name(path)

Basically, resolve_to_name returns the name of the view and it's parameters as a tuple, and the new {% url myvar %} takes this tuple and uses it to reverse the path with the view name and it's parameters.

If you don't like the filter approach it can also be done with a custom middleware.


Previous answer

You should check django-pagination, it's a really nice django application, easy tu use and gets the job done.

With django pagination the code to paginate an iterable would be:

{% load pagination_tags %}

{% autopaginate myiterable 10 %} <!-- 10 elements per page -->

{% for item in myiterable %} RENDERING CONTENT {% endfor %}

{% paginate %} <!-- this renders the links to navigate through the pages -->

myiterable can be anything that is iterable:list, tuple, queryset, etc

The project page at googlecode: http://code.google.com/p/django-pagination/

Guillem Gelabert
yes, I was using that, but it has ?page= as the way to paginate which doesn't work for me as my urls already have some query parameters that are important to preserve.
Paul Tarjan
Interesting, why isn't this type of {% url %} in actual django? And for the middleware approach, would it be less invasive? Rewriting the core {% url %} seems like it might break something down the road.
Paul Tarjan
With a middleware, instead of using request.path_info|resolve_to_url you will call resolve_to_url(request.path_info) in the middleware process_request(request) method, and add it to the request as a custom variable. Then it would be available in any template of your project.The new {% url %} will fail if you have a view and a variable with the same name.You can avoid this by creating your custom templatetag {% myurl %} and use this or the default one as needed.
Guillem Gelabert