所以我正在尝试设置一个django表单,我想使用Django Choicefield。现在对于选择字段,您必须提供它选择,这本质上是一个元组列表。
我正在尝试使用init(( 中声明的self.locales_allowed来代替类变量locales_allowed。
class XXX(forms.Form):
def init(self):
self.locales allowed = XX
locale = forms.ChoiceField(
label=label["locale"], choices=locales_allowed, required=True)
#How to use self.locales_allowed here?
如果我尝试这样做,我会不断NameError: name 'self' is not defined
。我正在寻找一种方法来完成这项工作。
直接答案是"你不能"。但是这里不需要使用实例变量进行选择,只需使用类变量即可,它没有self
的概念:
class MyForm(forms.Form):
LOCALES_ALLOWED = ...
locale = forms.ChoiceField(
label=label["locale"], choices=LOCALES_ALLOWED, required=True)
我LOCALES_ALLOWED
大写,因为这是 Python 中常量的约定,但实际上并不是必需的。这里的关键是你不需要实例变量,因为你所做的每个实例的选择都是相同的。