Django如何知道命令来呈现表单字段? [英] How does Django Know the Order to Render Form Fields?
问题描述
如果我有一个Django表单如:
If I have a Django form such as:
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
sender = forms.EmailField()
我调用这个形式的实例的as_table()方法,Django将渲染这些字段作为与上面指定的相同的顺序。
And I call the as_table() method of an instance of this form, Django will render the fields as the same order as specified above.
我的问题是Django如何知道类变量在哪里定义的顺序?
My question is how does Django know the order that class variables where defined?
(此外,如何覆盖此顺序,例如当我要添加一个字段从classe的 init 方法?)
(Also how do I override this order, for example when I want to add a field from the classe's init method?)
推荐答案
我回答了自己的问题。以下是未来参考的答案:
I went ahead and answered my own question. Here's the answer for future reference:
在Django form.py
中使用 __ new __
方法按照类中定义的顺序将类变量最终加载到 self.fields
中。 self.fields
是一个Django SortedDict
实例(定义在 datastructures.py
)。
In Django form.py
does some dark magic using the __new__
method to load your class variables ultimately into self.fields
in the order defined in the class. self.fields
is a Django SortedDict
instance (defined in datastructures.py
).
所以要覆盖这个,例如在我的例子中,你希望sender发送,但需要将它添加到 init 方法,你会这样做:
So to override this, say in my example you wanted sender to come first but needed to add it in an init method, you would do:
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
message = forms.CharField()
def __init__(self,*args,**kwargs):
forms.Form.__init__(self,*args,**kwargs)
#first argument, index is the position of the field you want it to come before
self.fields.insert(0,'sender',forms.EmailField(initial=str(time.time())))
这篇关于Django如何知道命令来呈现表单字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!