Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
        }
like image 434
user1507156 Avatar asked Feb 19 '23 21:02

user1507156


2 Answers

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?

like image 152
dani herrera Avatar answered Feb 27 '23 21:02

dani herrera


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'),
)
like image 20
Chris Pratt Avatar answered Feb 27 '23 19:02

Chris Pratt