I'm running into an issue where I set the initial value on a Choice field for County but when I render the form, the corresponding option doesn't render as selected. I can't figure out why this isn't working. Does anyone have any ideas?
Models.py
class State(models.Model):
name = models.CharField(max_length=30, db_index=True)
abbreviation = models.CharField(max_length=2, unique=True, db_index=True)
class County(models.Model):
name = models.CharField(max_length=30, db_index=True)
state = models.ForeignKey(State, on_delete=models.CASCADE)
Forms.py
class MyForm(forms.Form):
state = forms.ChoiceField(choices=[], required=False)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
county = kwargs.get('county')
state = kwargs.get('state')
state_qs = State.objects.all().values('id', 'name', 'abbreviation')
state_choices = [
(choice['id'], f"{choice['name']} ({choice['abbreviation']})") for choice in state_qs]
self.fields['state'].choices = [('', '---------')] + state_choices
county_qs = County.objects.select_related('state').filter(state__id=state).order_by(
'name').values('id', 'name', 'state', 'state__abbreviation')
county_choices = [
(choice['id'], f"{choice['name']}-{choice['state__abbreviation']}") for choice in county_qs]
initial = None
if county:
initial = county.id
self.fields['county'] = forms.ChoiceField(choices=county_choices, initial=initial)