gpt4 book ai didi

django - 设置 Django ModelChoiceField 的初始值

转载 作者:行者123 更新时间:2023-12-02 05:00:27 25 4
gpt4 key购买 nike

我有一个带有 m2m-Fields 到 OtherModel 的模型。

class OtherModel(models.Model)    
name = models.CharField(max_length=100, null=True)

class Model(models.Model)
name = models.CharField(max_length=100, null=True)
otherModel = models.ManyToManyField(OtherModel)

对于类模型,我使用普通的 FormSet()。对于 otherModel 类,我使用 formset_factory()

我只想允许从 OtherModel 的数据库中选择数据,所以我使用以下代码将 OtherModel 中的 CharField 名称更改为 ModelChoiceField:

def otherModel_formset(self, patientenID):

class OtherModelForm(ModelForm):
name= ModelChoiceField(queryset=OtherModel.objects.all())

def __init__(self, *args, **kwargs):
super(OtherModelForm, self).__init__(*args, **kwargs)


class Meta:
model = OtherModel
fields = ['name']

return formset_factory(form=OtherModelForm, max_num=10)

我可以将所选名称保存在 m2m 字段中,但在重新加载时他们什么都没有选择

示例:

<select id=some_id" name="some_name">
<option value="1"> HAWAII </option>
<option value="2"> ALASKA</option>
</select>

在示例中,ALASKA 在提交和重新加载时被选中,应该是这样的:

<select id=some_id" name="some_name">
<option value="1"> HAWAII </option>
<option value="2" **selected="selected"**> ALASKA</option>
</select>

但这站在html内容中:

<select id=some_id" name="some_name">
<option value="1"> HAWAII </option>
<option value="2"> ALASKA</option>
</select>

有人知道解决方案吗?

最佳答案

问题是一起使用 request.POSTinitial={'name': 'ALASKA'}。发生这种情况是因为 request.POST 的值总是覆盖参数“initial”的值,所以我们必须将它们分开。我的解决方案是使用这种方式。

views.py中:

if request.method == "POST":
form=OtherModelForm(request.POST)
else:
form=OtherModelForm()

forms.py 中:

class OtherModelForm(ModelForm):
name= ModelChoiceField(queryset=OtherModel.objects.all(), initial={'name': 'ALASKA'})

------------ 或------------

views.py中:

if request.method == "POST":
form=OtherModelForm(request.POST)
else:
form=OtherModelForm(initial={'name': 'ALASKA'})

forms.py 中:

class OtherModelForm(ModelForm):
name= ModelChoiceField(queryset=OtherModel.objects.all())

关于django - 设置 Django ModelChoiceField 的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17178573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com