Django - use Radio Buttons instead of Select for form component

I have several ModelFormused to build surveys whose models contain many questions (> 30 each). Multiple-choice questions are currently presented as an element <select>, but to improve UX, I would like to change this to switches.

Like ModelForm, I rely on django to automatically create fields on the form. Therefore, although I know that you can change each field in a form by doing this:

class SurveyForm(ModelForm):
   ...
   field_one = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect())

these definitions do not currently exist, and I will need to create at least 150 such definitions. I'm sure there is a better way to override widget selection (perhaps a ModelForm extension?). Or, alternatively, can I do this by attaching a widget to a field definition?

I looked through the documents and the source of Django, but I can not find where the widget is selected for the model fields with choiceskwarg.

+4
source share
2 answers

My first thought was what you could use formfield_overrides. However, this will not work because you want to override the widget for models.CharFieldone that has a choice and not all models.CharFields.

One approach would be to iterate over form fields in a method __init__and change any widgets from forms.Selectto forms.RadioInput.

class SurveyForm(forms.ModelForm):
    class Meta:
        model = Survey
        fields = ('field_one', 'field_two', ...)

    def __init__(self, *args, **kwargs):
        super(SurveyForm, self).__init__(*args, **kwargs)
        for field in self.fields.values():
            if isinstance(field.widget, forms.Select):
                field.widget = forms.RadioSelect()

If you have many such forms, you can extract the functionality in mixin.

+4
source
class MyModelForm(ModelForm):
    class Meta:
        widgets = {
            'field_one': forms.RadioSelect(),
        }

You might like it:

widgets = {field: forms.RadioSelect() for field in ['field_one', 'field_two']}
+4
source

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


All Articles