django form ModelChoiceField loads all state names while needed states which are mapped with current selected country
Posted
by
Sonu
on Stack Overflow
See other posts from Stack Overflow
or by Sonu
Published on 2013-10-22T09:50:29Z
Indexed on
2013/10/22
9:53 UTC
Read the original article
Hit count: 231
I am using modelChoiceField to display country and state into address form
class StateSelectionwidget(forms.Select): """ custom widget to state selection""" class Media: js = ('media/javascript/public/jquery-1.5.2.min.js', 'media/javascript/public/countrystateselection.js', ) class AddressForm(forms.Form): name = forms.CharField(max_length=30) country = forms.ModelChoiceField(queryset=[]) state = forms.ModelChoiceField(CountryState.objects, widget=StateSelectionwidget) def __init__(self, *args, **kwargs): super(AddressForm, self).__init__(*args, **kwargs) self.fields['country'].queryset = Country.objects.all()
Country model is used to store country names.
CountryState model is used to store all states which is foreign key to Country model
At the time of form loading i am getting all state names in dropdown while i want field to be blank by default.
If name field is empty at the time of form save i am getting error that name can not be empty but also getting all states into dropdown list while i want only the states which are mapped with current selected country.
© Stack Overflow or respective owner