Home > Software engineering >  Is it possible to map a field to a custom template radio button group?
Is it possible to map a field to a custom template radio button group?

Time:01-25

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?

CodePudding user response:

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.

CodePudding user response:

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 >
        {{ 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.

  • Related