1

I have a form that has a ModelChoiceField. I have created a custom widget for dealing with ModelChoiceFields, the widget extends forms.TextInput, so:

class SelectWidget(forms.TextInput):

    def __init__(self, attrs):
        super(SelectWidget, self).__init__(attrs)

    def render(self, name, value, attrs=None):
        value = "" if value is None else value

        # html stuff here

        return html_stuff

and on the form:

class Form(forms.ModelForm)
    address = forms.ModelChoiceField(queryset=models.Address.objects.all(),
                                     widget=SelectWidget(attrs={}))

I understand that when I submit the form, it will validate what ever was entered in the SelectWidget text input against the queryset provided to the ModelChoiceField which is what I want.

My question is: in the SelectWidget where I am overriding the render method, how can I access whatever queryset was passed to the ModelChoiceField in order to check it against the "value" attribute (if any) of the widget?

PT114
  • 931
  • 3
  • 10
  • 18

1 Answers1

2

You can access self.choices in your custom select widget which is a ModelChoiceIterator object

Aamir Rind
  • 38,793
  • 23
  • 126
  • 164