0

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)
charlieshu
  • 33
  • 5
  • Why you are not using ModelForm with ModelChoiceField – kkiat Mar 14 '20 at 18:40
  • I need to use .values() on the queryset to avoid loading other fields into memory when the queryset is evaluated. I believe that this prevents me from using the ModelChoiceField, but I may be missing something. – charlieshu Mar 15 '20 at 02:06
  • I think this is what you are looking for https://stackoverflow.com/questions/3167824/change-django-modelchoicefield-to-show-users-full-names-rather-than-usernames – kkiat Mar 15 '20 at 06:23

0 Answers0