django、uni_form和python的__init__()函数 - 如何向表单传递参数?
我有点搞不懂 Python 中的 __init__
( ) 函数是怎么工作的。我想在 Django 中创建一个新的表单,并使用 uni_form 帮助工具以自定义的方式显示这个表单,使用字段集。不过,我给表单传递了一个参数,这个参数应该稍微改变表单的布局,但我不知道怎么让它工作。以下是我的代码:
class MyForm(forms.Form):
name = forms.CharField(label=_("Your name"), max_length=100, widget=forms.TextInput())
city = forms.CharField(label=_("Your city"), max_length=100, widget=forms.TextInput())
postal_code = forms.CharField(label=_("Postal code"), max_length=7, widget=forms.TextInput(), required=False)
def __init__(self, city, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
if city == "Vancouver":
self.canada = True
if self.canada:
# create an extra uni_form fieldset that shows the postal code field
else:
# create the form without the postal code field
但是,这个问题的原因在于,self.canada 在 __init__
之外似乎从来没有任何值。因此,尽管我把这个参数传递给了函数,但我在我的类中却无法使用这个值。我找到了一种解决方法,就是在 __init__
中完全使用 self.fields 来创建表单,但这样看起来很难看。我该如何在 __init__
之外使用 self.canada 呢?
1 个回答
4
你可能对Python中的类是怎么工作的理解有些偏差。你在类里面试图运行一些代码,但这些代码并不在任何函数里,这样做一般是行不通的,特别是当这些代码依赖于__init__
里面发生的事情时。那段代码会在类第一次被导入时执行,而__init__
是在每次创建表单的时候执行的。
最好的办法是把字段组放在表单里,但当加拿大的值为真时就不显示它们。你的__init__
代码可以根据这个值把这些字段设置为required=False
,这样就不会出现验证错误了。