Django 如何知道呈现表单字段的顺序? [英] How does Django Know the Order to Render Form Fields?

查看:39
本文介绍了Django 如何知道呈现表单字段的顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个 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?

(还有我如何覆盖这个顺序,例如当我想从类的 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).

所以要覆盖这个,在我的例子中假设你希望发件人先出现,但需要将它添加到 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆