Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/django/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
呈现表单时忽略Django选择字段初始值_Django - Fatal编程技术网

呈现表单时忽略Django选择字段初始值

呈现表单时忽略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)

我遇到了一个问题,我在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 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,但我可能遗漏了一些东西。我想这就是您要寻找的