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
Tags:
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. Allow any view (probably a generic view) to accept captured URL variables into extra_context. by orblivion 4 years, 6 months ago
  2. ModelForm-based create_update generic views by carljm 6 years, 10 months ago
  3. Simple random file CAPTCHA by jeverling 3 years, 2 months ago
  4. Variable resolving URL template tag by UloPe 6 years, 2 months ago
  5. render_partial by hachaboob 6 years, 8 months ago

Comments

Please login first before commenting.