python - regexfield - field type form django




DJANGO: tag optgroup ModelChoiceField (2)

Ecco un buon frammento:

Scelta campo e Seleziona widget con Optgroup facoltativi: http://djangosnippets.org/snippets/200/

Come posso impostare il tag optgroup ModelChoiceField ?

Questo è un esempio:

models.py

class Link(models.Model):
    config = models.ForeignKey(Config)
    name = models.URLField(u'Name', null=True, max_length=50)
    gateway = models.IPAddressField(u'Gateway', null=True)
    weight = models.IntegerField(u'Weight', null=True)
    description = models.TextField(u'Description', blank=True)

def __unicode__(self):
    return self.name

forms.py

class LinkForm(ModelForm):
    config = ModelChoiceField(queryset=Config.objects.all(), empty_label="Choose a link",widget=GroupedSelect())

class Meta:
    model = Link

Mi piacerebbe rendere il mio ChoiceField in questo modo:

example.html

<select id="id_config" name="config">
    <option selected="selected" value="">Choose a link</option>
    <optgroup label="Configuration" >
        <option value="8">Address: 192.168.1.202/255.255.255.0 </option>
        <option value="9">Address: 192.168.1.240/255.255.255.0 </option>
        <option value="10">Address: 192.168.3.1/255.255.255.0 </option>
    </optgroup>
</select>

** AGGIORNAMENTO * *

Ho risolto il mio problema in questo modo:

class GroupedSelect(Select):
    def render(self, name, value, attrs=None, choices=()):
        if value is None: value = ''
        final_attrs = self.build_attrs(attrs, name=name)
        output = [format_html('<select{0}>', flatatt(final_attrs))]
        for index, option_gp in enumerate(self.choices):
            if index == 0:
                option_value = smart_unicode(option_gp[0])
                option_label = smart_unicode(option_gp[1])
                output.append(u'<option value="%s">%s</option>' %  (escape(option_value), escape(option_label)))
                output.append('<optgroup label = "Configuration">')
            elif index!=0 and index <= len(self.choices):
                option_value = smart_unicode(option_gp[0])
                option_label = smart_unicode(option_gp[1])
                output.append(u'<option value="%s">%s</option>' % (escape(option_value), escape(option_label)))          
        output.append(u'</optgroup>')
        output.append(u'</select>')
        return mark_safe('\n'.join(output))

Non hai bisogno di creare alcun campo personalizzato, Django già fa il lavoro, basta passare le scelte ben formattate:

MEDIA_CHOICES = (
 ('Audio', (
   ('vinyl', 'Vinyl'),
   ('cd', 'CD'),
  )
 ),
 ('Video', (
   ('vhs', 'VHS Tape'),
   ('dvd', 'DVD'),
  )
 ),
)




django-forms