Login

Snippets by orblivion

Snippet List

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

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.

Read More

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

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.

  • urls
  • views
Read More

orblivion has posted 2 snippets.