我想要做的是根据页面隐藏或显示一些选项。 例如,
models.py
USA = 'usa'
FRANCE = 'france'
CHINA = 'china'
GERMANY = 'germany'
SPAIN = 'spain'
TOPICS = (
(USA, 'USA'),
(FRANCE, 'France'),
(CHINA, 'China'),
(GERMANY, 'Germany'),
(SPAIN, 'Spain'),
)
topic = models.CharField(
choices=TOPICS,
default=USA,
)
对于一个页面,我想强制用户不要选择美国,所以我想在表单中隐藏美国,并更改默认值。我怎样才能做到这一点?
这是我当前的代码。 类 AForm(forms.ModelForm):
class Meta:
model = A
fields = ['topic',]
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['topic'].choices = ['France', 'Germany', 'Spain']
有错误。
ValueError: too many values to unpack (expected 2)
我用随机的两个字符替换了它,例如ab
其中一个字符作为一种选择出现在表单上,即使我没有在模型上定义它。我仍然不明白如何将覆盖的选择与模型关联起来。 ModelForm
的正确方法是什么?
最佳答案
这与 ModelForm 无关,而是与选择的定义方式有关 - 选择应该是 (value, label)
元组的列表(看看您如何在模型中定义选择),而不是值列表。你想要的是:
self.fields['topic'].choices = [
('france','France'),
('germany', 'Germany'),
('spain', 'Spain')
]
或者(更好):
self.fields['topic'].choices = [
choice for choice in YourModel.TOPICS
if choice[0] in ('france', 'germany', 'spain')
]
关于python - Django 表单;使用 ModelForm 覆盖选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53810636/