4

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)
        }
username
  • 4,258
  • 1
  • 16
  • 26
user1507156
  • 539
  • 1
  • 7
  • 12

2 Answers2

5

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?

Community
  • 1
  • 1
dani herrera
  • 48,760
  • 8
  • 117
  • 177
  • Choices should *not* be a queryset if the OP is using `forms.ChoiceField`. Choices needs to be a tuple of key/value pair tuples. Only if the OP were using `forms.ModelChoiceField` should they use a queryset. – Chris Pratt Jul 11 '12 at 14:52
  • @ChrisPratt, thanks about your comment. I mean that in second scenario, where name is a modelChoiceField, choices should be a query set. You agree? Please, be free to fix my answer. – dani herrera Jul 11 '12 at 15:06
3

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'),
)
Chris Pratt
  • 232,153
  • 36
  • 385
  • 444