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
Tags:
urls views
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. Allow any view (probably a generic view) to accept POST variables into extra_context by orblivion 4 years, 6 months ago
  2. A action decorator for URLs by Batiste 7 years, 1 month ago
  3. direct to template from a subdir by Scanner 6 years, 7 months ago
  4. Quickly check templates while sketching them out by amr-mostafa 8 years, 1 month ago
  5. Cheap direct_to_tempalte patterns by jjdelc 6 years, 6 months ago

Comments

Please login first before commenting.