Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add multiple fields sorting #21

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 17 additions & 5 deletions django_sorting/middleware.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
def get_field(self):
ordering = []
try:
field = self.REQUEST['sort']
# REQUEST is deprecated as of Django 1.7.
field = self.POST.get('sort')
if field is None:
field = self.GET.get('sort', '')
except (KeyError, ValueError, TypeError):
field = ''
return (self.direction == 'desc' and '-' or '') + field
pass
else:
for key in field.split(','):
if key:
ordering.append((self.direction == 'desc' and '-' or '') + key)
return ordering

def get_direction(self):
try:
return self.REQUEST['dir']
# REQUEST is deprecated as of Django 1.7.
value = self.POST.get('dir')
if value is None:
value = self.GET.get('dir', '')
return value
except (KeyError, ValueError, TypeError):
return 'desc'

Expand All @@ -19,4 +31,4 @@ class SortingMiddleware(object):
"""
def process_request(self, request):
request.__class__.field = property(get_field)
request.__class__.direction = property(get_direction)
request.__class__.direction = property(get_direction)
24 changes: 13 additions & 11 deletions django_sorting/templatetags/sorting_tags.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from django import template
from django.core.exceptions import FieldError
from django.http import Http404
from django.conf import settings

Expand All @@ -22,12 +23,9 @@ def anchor(parser, token):
bits = [b.strip('"\'') for b in token.split_contents()]
if len(bits) < 2:
raise TemplateSyntaxError, "anchor tag takes at least 1 argument"
try:
title = bits[2]
except IndexError:
title = bits[1].capitalize()
return SortAnchorNode(bits[1].strip(), title.strip())

sort_tag = ','.join(bits[1:-1])
return SortAnchorNode(sort_tag, bits[-1].strip())


class SortAnchorNode(template.Node):
"""
Expand Down Expand Up @@ -59,8 +57,11 @@ def render(self, context):
else:
sortdir = ''
if sortby == self.field:
getvars['dir'] = sort_directions[sortdir]['inverse']
icon = sort_directions[sortdir]['icon']
try:
getvars['dir'] = sort_directions[sortdir]['inverse']
icon = sort_directions[sortdir]['icon']
except KeyError:
icon = DEFAULT_SORT_UP
else:
icon = ''
if len(getvars.keys()) > 0:
Expand Down Expand Up @@ -94,10 +95,11 @@ def render(self, context):
key = self.queryset_var.var
value = self.queryset_var.resolve(context)
order_by = context['request'].field
if len(order_by) > 1:
if len(order_by) > 0:
try:
context[key] = value.order_by(order_by)
except template.TemplateSyntaxError:
context[key] = value.order_by(*order_by)
context[key].first() # evaluate query to protect from being sorted by non model field
except (template.TemplateSyntaxError, FieldError):
if INVALID_FIELD_RAISES_404:
raise Http404('Invalid field sorting. If DEBUG were set to ' +
'False, an HTTP 404 page would have been shown instead.')
Expand Down