Login

Allow any view (probably a generic view) to accept captured URL variables into extra_context.

Author:
orblivion
Posted:
October 28, 2010
Language:
Python
Version:
1.2
Score:
0 (after 0 ratings)

If your URL pattern looks like:

urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/(?P<obj_id>\d+)/new_thing$', create_object, {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', extra_context: {:this":"that"}), )

You will receive an error, because the create_update view doesn't have a parameter called "obj_id". Supposing you want that variable in the URL, and furthermore let's say you wanted to do something with it in the template. With this function, you can wrap the view, and add the parameter capture_to_context, which maps URL variables to template variables:

urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/(?P<obj_id>\d+)/new_thing$', view_url_vars_to_context(create_object), {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', 'url_vars_to_context':{'obj_id':'objID'}, extra_context: {:this":"that"}}), )

Now objID will be a variable in your template, with the value given to obj_id.

This is good for generic views, but there's no reason you couldn't use it for your own views if you really wanted, as long as you had an "extra_context" parameter.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import inspect

# changes a view such that it captures specified variables from the URL and sends it to the context
def view_url_vars_to_context(view):
    def view_with_uv2c(request, url_vars_to_context = {}, extra_context = {}, *args, **kwargs):

        basicargs = inspect.getargspec(view).args

        # This is going to prevent some sort of confusion at some point.
        if set(url_vars_to_context.keys()) & set(basicargs):
            raise ValueError("Context variable names from URL can't be arguments expected by generic view.")

        for varname in url_vars_to_context.keys():
            if varname not in kwargs.keys():
                raise ValueError("URL variable %s does not exist" % varname)

        for k in kwargs.keys():
            if k in url_vars_to_context:
                context_var_name = url_vars_to_context[k]
                extra_context[context_var_name] = kwargs[k]
                del kwargs[k]
        
        return view(request, extra_context=extra_context, *args, **kwargs)
    return view_with_uv2c

More like this

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

Comments

Please login first before commenting.