Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.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_Django Forms_Django Models - Fatal编程技术网

Django:定义自己的表单字段

Django:定义自己的表单字段,django,django-forms,django-models,Django,Django Forms,Django Models,我写了一个这样的表单字段 //forms.py hostAdress = forms.CharField(required = False, label = ('#content'), initial = ('#content')) adminHostAdress = hostAdress userHostAdress = hostAdress 它的显示是正确的,但是当一个用户想

我写了一个这样的表单字段

//forms.py

hostAdress = forms.CharField(required = False,
                             label = ('#content'),
                             initial = ('#content'))
adminHostAdress = hostAdress
userHostAdress = hostAdress
它的显示是正确的,但是当一个用户想要保存表单时,我带着填充的字段返回表单,没有发生其他任何事情

当我写作时

adminHostAdress = forms.CharField(required = False,
                                  label = ('#content'),
                                  initial = ('#content'))
userHostAdress = forms.CharField(required = False,
                                 label = ('#content'),
                                 initial = ('#content'))
所有的工作,但我重复我自己,我有更多的这些领域,我想写一次


有什么想法吗?

您的第一个示例只是将相同的
CharField
分配给两个单独的表单变量,因此本质上它们共享Django表单字段的相同实例。如果愿意,您可以尝试以下方法:

class MyForm(forms.Forms):
    def __init__(self, *args, **kwargs):
        super(MyForm, self).__init__(*args, **kwargs)
        for field_name in ["adminHostAdress", "userHostAdress", ...]:
            self.fields[field_name] = forms.CharField(
                required = False,
                label = ('#content'),
                initial = ('#content'))
但在我看来,这不太容易理解,也不会特别节省你很多时间

好吧,那太恶心了;)是否没有办法轻松获得表单字段的两个独立实例?