django form radio input layout

前端 未结 4 882
醉话见心
醉话见心 2021-01-02 17:05

What is the \"djangoy\" way to approach this problem:

In my form class, I have a forms.ChoiceField whose widget is a forms.RadioSelect widget, one of whose choices n

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-02 17:42

    I would do this by subclassing RadioFieldRenderer and attaching it to a custom widget:

    # forms.py
    from django import forms
    from django.forms.widgets import RadioSelect, RadioFieldRenderer
    from django.template.loader import render_to_string
    from myapp.models import RatherComplicatedModel
    
    
    class MyRadioFieldRenderer(RadioFieldRenderer):
        def render(self):
            return render_to_string(
                'my_radio_widget.html',
                        {'field': self})
    
    
    class MyRadioSelect(RadioSelect):
        renderer = MyRadioFieldRenderer
    
    
    class RatherComplicatedForm(forms.ModelForm):
        RADIO_CHOICES = (
            ('none', "No Textbox"),
            ('one', "One Textbox: "),
        )
        rad = forms.ChoiceField(widget=MyRadioSelect(),choices=RADIO_CHOICES)
    
        class Meta:
            model = RatherComplicatedModel
    

    Then the template:

    #my_radio_widget.html
    
      {% for choice in field %}
    • {% endfor %}

提交回复
热议问题