呈现表单时忽略Django选择字段初始值
我遇到了一个问题,我在County的选择字段上设置了初始值,但是当我呈现表单时,相应的选项不会呈现为选中状态。我不明白这为什么不起作用。有人有什么想法吗 Models.py呈现表单时忽略Django选择字段初始值,django,Django,我遇到了一个问题,我在County的选择字段上设置了初始值,但是当我呈现表单时,相应的选项不会呈现为选中状态。我不明白这为什么不起作用。有人有什么想法吗 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 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)
为什么不将ModelForm与ModelChoiceFieldI一起使用需要在queryset上使用.values(),以避免在计算queryset时将其他字段加载到内存中。我相信这会阻止我使用ModelChoiceField,但我可能遗漏了一些东西。我想这就是您要寻找的