﻿id	summary	reporter	owner	description	type	status	component	version	severity	resolution	keywords	cc	stage	has_patch	needs_docs	needs_tests	needs_better_patch	easy	ui_ux
1502	Make (?P) url parameters available to filter a generic view's queryset.	benjaminlyu@…	Jacob	"Example Problem:

1) http://example.com/users/ - lists all the users.

2) http://example.com/users/(?P<mystr>[a-z]+)/ - For given string, list all the users with a username beginning with that string.

(1) is a simple generic view. However, one currently must write a custom view to come up with a QuerySet for (2). What we could do is just take the generic view used for (1) and filter that QuerySet down more.


The code listed here is an example solution using a custom wrapper to the object_list generic view. A real solution would patch the generic views. 'myproject.object_list' (shown here) differs from the generic object_list by two items in its method signature: extra_lookup_kwargs={} and **kwargs; some of its code can be used to filter the queryset.

myproject/urls.py
{{{
info_dict = {
  'queryset': MyModel.objects.all(),
  'extra_lookup_kwargs': { 'mystr': 'name__istartswith'}
}

urlpatterns = patterns('',
    (r'^users/$', 'myproject.views.object_list', info_dict),
    (r'^users/(?P<mystr>.+)/$', 'myproject.views.object_list', info_dict),
)
}}}

myproject/views.py:
{{{
from django.template import loader
from django.views.generic import list_detail

def object_list(request, queryset, paginate_by=None, allow_empty=False,
  template_name=None, template_loader=loader,
  extra_context={}, context_processors=None, template_object_name='object',
  extra_lookup_kwargs={}, **kwargs):

  extra_lookup_dict = {}
  for param in kwargs:
    if param in extra_lookup_kwargs:
      extra_lookup_dict[extra_lookup_kwargs[param]] = kwargs[param]
  if len(extra_lookup_dict) > 0:
    newqueryset = queryset.filter(**extra_lookup_dict)
  else:
    newqueryset = queryset

  return list_detail.object_list(request=request, queryset=newqueryset,
    paginate_by=paginate_by, allow_empty=allow_empty,
    template_name=template_name, template_loader=template_loader,
    extra_context=extra_context, context_processors=context_processors,
    template_object_name=template_object_name)

}}}
"	enhancement	closed	Generic views	magic-removal	normal	wontfix			Unreviewed	0	0	0	0	0	0
