Generic object_detail view filterable by multiple url values

 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. Allow any view (probably a generic view) to accept captured URL variables into extra_context. by orblivion 3 years, 5 months ago
  2. Extend generic view object_list to support paginate_by via cookies by kersurk 3 years, 3 months ago
  3. MultiSelect checkbox iterator template filter by ke1g 3 years, 8 months ago
  4. Middleware to resolve current URL to module and view by kuchin 3 years, 9 months ago
  5. Add multiple parameters to the current url by cschand 5 years, 9 months ago

Comments

(Forgotten your password?)