Custom rendering of a radio select in the form of django / single element access?

I have a form like this:

CHOICES = [ ('a', 'a_value'), ('b', 'b_value'), ('c', 'c_value') ] self.fields["choice"] = forms.ChoiceField( widget=RadioSelect(), choices=CHOICES, ) 

How can I select one element of this form field in my template? I want to be able to do something like:

 <tr><td>{{form.choice.a}}</td><td>some custom extra field</td></tr> 

Or is there another way to change the way RadioSelect is rendered?

+4
source share
3 answers

You cannot do this through parameters or something, the way it is rendered is hardcoded in the widget class! See for example. http://code.djangoproject.com/browser/django/trunk/django/forms/widgets.py : RadioSelect.render (-> RadioFieldRenderer.render); subclass and override the rendering method, and then use it in your form myfield = forms.MultipleChoiceField(widget=MyWidget(...)) .

+1
source

See the full document - https://docs.djangoproject.com/en/dev/ref/forms/widgets/#radioselect

  {% for radio in form.my_radio_select%}
 - {{radio.choice_label}}
 - {{radio.tag}}
 {% endfor%}
+6
source

I worked on this for several hours, trying to find a way to use my own renderer on RadioSelect, but there is no way to pass the selection number. Instead, I went for kludgey, but a simple approach. Added __init__ function to my form:

 def __init__(self, *args, **kwargs): super(FormName, self).__init__(*args, **kwargs) self.radiofield_choice = re.findall(r'<li>(.+?)</li>', unicode(self['radiofield_name'])) 

Uses the default rendering of RadioSelect to create a widget, and then parses the individual HTML code. You can even combine this with certain options to create a dictionary instead of a list.

In my template, I used {{ form.radiofield_choice.0|safe }} to render only the first element. Increase zero to get other items.

If for some reason you need only input fields without adding labels, use r'(<input.+/>)' .

+1
source

Source: https://habr.com/ru/post/1312075/


All Articles