Login

Generic object_detail view filterable by multiple url values

Author:
jlorich
Posted:
May 16, 2011
Language:
Python
Version:
1.3
Score:
1 (after 1 ratings)

This view acts as an extension to the object_detail generic view in django.views.generic.object_list. The standard generic view can only filter the queryset by object_id or slug; this view allows you to filter by any parameter you like, as well as multiple parameters.

The usage is the same as the standard object_detail view except that you must also give the parameter 'filters', which should be an array of what you would like to filter the url values as, and instead of 'slug' or 'object_id' as the regex parameter in the URL, use 'value1', 'value2', etc.

Example: If you have a list of companies, each with multiple branches, you may want a branch details page. A URL for this may look as follows: http://www.mysite.com/company/company-slug/branch-slug/. To implement this simply use the urlpattern example give,

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
from django.views.generic.list_detail import object_detail

def filtered_object_detail(request, queryset,
        template_name=None, template_name_field=None,
        template_loader=loader, extra_context=None,
        context_processors=None, template_object_name='object',
        mimetype=None, filters=None, **kwargs):
    
    """
    Generic detail of an object derived by filtering a queryset by multiple parameters

    Templates: ``<app_label>/<model_name>_detail.html``
    Context:
        object
            the object
    """
    
    args = {}
    
    for i in range(0, len(kwargs)):
        if 'value' + str(i+1) in kwargs.keys() and len(filters) >= i
            args[filters[i]] = kwargs['value' + str(i+1)]
    
    queryset = queryset.filter(**args)

    if len(queryset) > 0:
        object_id = str(queryset[0].id)
    else:
        object_id = None

    return object_detail(request, queryset, object_id,
        None, None, template_name, template_name_field,
        template_loader, extra_context, context_processors,
        template_object_name, mimetype
    )


urlpattern example:

    url(r'^company/(?P<value1>[a-zA-Z0-9\-\_\.]+)/(?P<value2>[a-zA-Z0-9\-\_\.]+)/$',
        filtered_object_detail,
        {
            "queryset" : Branch.objects.all(),
            'filters': ['company__slug', 'slug'],
        }
    ),

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.