我遇到一个问题,我在“县”的“选择”字段上设置了初始值,但是在渲染表单时,相应的选项未呈现为选中状态。我不知道为什么这不起作用。有人有什么想法吗?
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)