Is it possible to map a field to a custom template radio button group?

Question in the title.

I have a form like so

class SelectTypeForm(forms.Form):

the_type = forms.CharField(max_length=100)

I have a custom template with a radio button group. How can make the field get the selected value?

You can use the built-in RadioSelect widget and pass in a custom template path to the template_name argument in the form field definition.

For example:

from django import forms

class MyForm(forms.Form):
    my_field = forms.ChoiceField(
        widget=forms.RadioSelect(template_name='my_app/custom_radio_template.html'),
        choices=(('option1', 'Option 1'), ('option2', 'Option 2')),
    )

Then you can create your custom radio button template in my_app/templates/my_app/custom_radio_template.html and use the {{ forloop.counter }} variable to output the radio button values and labels correctly.

The template_name argument is not a valid argument for the RadioSelect widget. Instead of template_name, you should use attrs argument.

class MyForm(forms.Form):
    my_field = forms.ChoiceField(
        widget=forms.RadioSelect(attrs={'template': 'my_app/custom_radio_template.html'}),
        choices=(('option1', 'Option 1'), ('option2', 'Option 2')),
    )

You should also note that the attrs value is a dictionary and the key 'template' is not a valid HTML attribute.

class MyForm(forms.Form):
    my_field = forms.ChoiceField(
        widget=forms.RadioSelect(attrs={'class': 'custom-radio'}),
        choices=(('option1', 'Option 1'), ('option2', 'Option 2')),
    )

Then in your template, you can use the class to target the radio buttons and apply custom styles or layouts.

{% for radio in form.my_field %}
    <div class="custom-radio">
        {{ radio }}
    </div>
{% endfor %}

It's important to note that the attrs argument is passed to the widget, so it will affect all the rendered elements, not only the radio buttons, so you should use the class in your CSS to target only the radio buttons.

Go away from your CharField. Hopefully I understand you correctly and you want to have a radio-button-group with multiple options. Each option represents a string. If the user decides to click the second presented radio-button, the string 'is_stored' gets stored.

class SelectTypeForm(forms.Form):
    choose_type = forms.ChoiceField(label='your type field', choices=(
        ('type_a', 'This string'),
        ('type_b', 'is stored'),
        ('type_c', 'if selected')
    ), widget=forms.RadioSelect, initial='type_b')

If this is not what you meant, please provide your 'custom template with a radio button group'.

Back to Top