Django : Use widget to limit choices in a ModelForm

My model form inherit from subsystem form. I want to limit choices for the user in the form. (specially the name) I know I have to use widgets. But It doesn't work.

I have to use SubsytemForm.

SUBSYSTEM_CHOICES = (a1,a2,a3)


class Subsystem(models.Model):
    name = models.CharField("Name", max_length=20)


class SubsytemForm(forms.ModelForm):   
    class Meta:
        model = Subsystem
        widgets = {
            'name': ChoiceField(widget=RadioSelect, choices=SUBSYSTEM_CHOICES)
        }

From django model forms documentation:

If you explicitly instantiate a form field like this, Django assumes that you want to completely define its behavior; therefore, default attributes (such as max_length or required) are not drawn from the corresponding model. If you want to maintain the behavior specified in the model, you must set the relevant arguments explicitly when declaring the form field.

You can try with:

class SubsytemForm(forms.ModelForm):  
    name =  forms.ChoiceField(widget=RadioSelect, choices= choices )
    class Meta:
        model = Subsystem

Also you can

class SubsytemForm(forms.ModelForm):  
    class Meta:
        model = Subsystem
    def __init__(self, *args, **kwargs):
        self.name_choices = kwargs.pop('name_choices', None)
        super(SubsytemForm,self).__init__(*args,**kwargs)
        self.fields['name'].queryset= self.name_choices  

and send name_choices as parameter in SubsytemForm creation. Remember that choices should be a query set.

Also, you should read How do I filter ForeignKey choices in a Django ModelForm?


SUBSYSTEM_CHOICES is not a valid value for the choices attribute because it has no key/value pairs. You need something like:

SUBSYSTEM_CHOICES = (
    (a1, 'a1 Display'),
    (a2, 'a2 Display'),
    (a3, 'a3 Display'),
)