Login

Allow any view (probably a generic view) to accept POST variables into extra_context

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

Supposing you wanted to use a generic view, but you wanted to pass something over POST to show up in the resultant template. Perhaps you're creating a new object, and you want to pre-populate some hidden fields.

urlpatterns = patterns('django.views.generic.create_update', url(r'^obj/new$', view_post_vars_to_context(create_object), {'form_class': ThingForm, 'template_name': 'thing/new_thing.html', 'post_vars_to_context':{'obj_id':'objID'}, extra_context: {:this":"that"}}), )

Now objID will be a variable in your template, with the value passed via POST in the variable 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.

For security, since POST variables aren't cleansed automatically, this only accepts values of "_" and "-". If you feel confident, you can alter this to your needs.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
import string

# changes a view such that it sends specified POST vars to the context
def view_post_vars_to_context(view):
    def view_with_pv2c(request, post_vars_to_context = {}, extra_context={}, *args, **kwargs):
        if request.method == "POST":
            for k, v in request.POST.items():
                if k in post_vars_to_context.keys():
                    if set(v) <= set(string.letters + string.digits + "-_"): # restrict to alphanumeric, plus _ and -, since POST isn't otherwised cleansed
                        context_var_name = post_vars_to_context[k]
                        extra_context[context_var_name] = v

        return view(request, extra_context=extra_context, *args, **kwargs)
    return view_with_pv2c

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.