Login

Dynamically change a form select widget to a hidden widget

Author:
epicserve
Posted:
July 1, 2009
Language:
Python
Version:
1.0
Score:
0 (after 0 ratings)

This is an example of how you change a ChoiceField select widget into a hidden field if the right GET variable is passed. In this example code it would change the select widget into something like the following if something like "?d=3" was passed.

<p><label for="id_designation">Designation</label>Designation Option<input type="hidden" name="designation" value="3" id="id_designation" /></p>

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
"""Change a ChoiceField select widget into a hidden field if the right GET variable is passed"""

""" code for your view """
designation  = request.GET.get('d')
choice       = {}

if not designation:
	form = Form()
else:
	"""Setup the designation field as a hidden field if the right get variable was passed"""
	
	form = Form(initial={ 'designation': designation })
	from django.forms import widgets

	for item in form.fields['designation'].choices:
		if str(item[0]) == designation:
			form.fields['designation'].widget = widgets.HiddenInput()
			choice['designation'] = str(item[1])

return render_to_response('my-form.html', { 'form': form, 'choice': choice }, context_instance=RequestContext(request))


""" code for your template """
<p>{{ form.designation.label_tag }}{% if choice.designation %}{{ choice.designation }}{% endif %}{{ form.designation }}</p>

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.