更新时间:2023-10-05 22:44:46
Django 1.9 添加了一个新的 Form
属性,field_order
,允许对字段进行排序,而不管它们在类中的声明顺序.
Django 1.9 adds a new Form
attribute, field_order
, allowing to order the field regardless their order of declaration in the class.
class MyForm(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
author = forms.CharField()
notes = form.CharField()
field_order = ['author', 'summary']
field_order
中缺少的字段保持它们在类中的顺序,并附加在列表中指定的字段之后.上面的示例将按以下顺序生成字段:['author', 'summary', 'description', 'notes']
Missing fields in field_order
keep their order in the class and are appended after the ones specified in the list. The example above will produce the fields in this order: ['author', 'summary', 'description', 'notes']
查看文档:https://docs.djangoproject.com/en/stable/ref/forms/api/#notes-on-field-ordering
我遇到了同样的问题,我在 Django CookBook 中找到了另一种重新排序字段的技术:
I had this same problem and I found another technique for reordering fields in the Django CookBook:
class EditForm(forms.Form):
summary = forms.CharField()
description = forms.CharField(widget=forms.TextArea)
class CreateForm(EditForm):
name = forms.CharField()
def __init__(self, *args, **kwargs):
super(CreateForm, self).__init__(*args, **kwargs)
self.fields.keyOrder = ['name', 'summary', 'description']