Login

ChoiceField with widget in choice

Author:
alfonsopalomares
Posted:
March 17, 2009
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

This code creates a widget that we used to generate a list of radiobuttons as follows:

  • Radio button 1 --Widget__1

  • Radio button 2 --Widget__2

  • Radio button 3 --Widget__3

How to use it is:

`ImagenForm class (forms.ModelForm): widget1 = forms.BooleanField () widget2 = forms.TextInput widget3 = forms.ModelChoiceField (queryset = Modelo.objects.all ()) widget4 = forms.FileInput

optConListas = ChoiceWithOtherField (choices = [(2, 'widget1' widget1), (3, 'widget2' widget3.widget), (4, "widget2" widget2), (5, 'widget4' widget4)])`
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
class ChoiceWithOtherRenderer(forms.RadioSelect.renderer):
  def __init__(self, *args, **kwargs):
    super(ChoiceWithOtherRenderer, self).__init__(*args, **kwargs)

  def __iter__(self):
    for input in self.choices:
      id = '%s_%s' % (self.attrs['id'], input[0]) if 'id' in self.attrs else ''
      label_for = ' for="%s"' % id if id else ''
      checked = '' if not force_unicode(input[0]) == self.value else 'checked="true" '
      html = '<label%s><input type="radio" id="%s" value="%s" name="%s" %s/> %s</label> %%s' %  
      (label_for, id, input[0], self.name, checked, input[1])
      
      yield html 

class ChoiceWithOtherWidget(forms.MultiWidget):
  def __init__(self, choices):
    widgets = [forms.RadioSelect(choices=choices, renderer=ChoiceWithOtherRenderer),]
    for choice in choices:
      widgets.append(choice[2])
    
    super(ChoiceWithOtherWidget, self).__init__(widgets)

  def decompress(self, value):
    if not value:
      return [None, None]
    return value

  def format_output(self, rendered_widgets):
    render = []
    for widget in rendered_widgets[1:]:
      render.append(widget)

    render = tuple(render)
    return rendered_widgets[0] %  render

class ChoiceWithOtherField(forms.MultiValueField):
  def __init__(self, *args, **kwargs):
    fields = [
    forms.ChoiceField(widget=forms.RadioSelect(renderer=ChoiceWithOtherRenderer), *args, **kwargs),
    ]
    widget = ChoiceWithOtherWidget(choices=kwargs['choices'])
    kwargs.pop('choices')
    self._was_required = kwargs.pop('required', True)
    kwargs['required'] = False
    super(ChoiceWithOtherField, self).__init__(widget=widget, fields=fields, *args, **kwargs)

  def compress(self, value):
    if self._was_required and not value or value[0] in (None, ''):
      raise forms.ValidationError(self.error_messages['required'])
    if not value:
      return [None, u'']
    return (value[0], value[1] if force_unicode(value[0]) == force_unicode(self.fields[0].choices[-1][0]) else u'')

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks 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

CrabbyPete (on July 16, 2011):

I'm trying to get this to work, but this is not valid Python optConListas = ChoiceWithOtherField (choices = [(2, 'widget1' widget1), (3, 'widget2' widget3.widget), (4, "widget2" widget2), (5, 'widget4' widget4)])`

#

Please login first before commenting.