重新排序modelform字段

时间:2011-02-22 02:10:16

标签: django django-models django-templates django-forms

我需要重新排序来自另一个基类的模型中的字段。无法找到解决方案。下面代码段中的“地址”始终显示在HTML模板的开头。如何使用渲染模板进一步向下移动?提前谢谢。

class Address:
   street= ...
   city= ...

class Customer(Address):
   name = ...
   ...

class CustomerForm(ModelForm):
   def __init__(...)
        super(CustomerForm, self).__init__(*args, **kw)
        self.fields.keyOrder=[
        'name',
        'Address',  #<-- I want "Address" appear after the name in my template
                    #<-- This obviously is not the right code.
   class Meta:
      model = Customer

-P

5 个答案:

答案 0 :(得分:7)

重新订购非常繁琐:

# django's SortedDict stores ordering of its fields in this list-type attribute:
keyorder = self.fields.keyOrder

# Remove fields which we want to displace:
keyorder.remove('street')
keyorder.remove('city')

# Get position where we want them to put in:
i = keyorder.index('name') + 1

# Insert items back into the list:
keyorder[i:i] = ['city', 'street']

最好只是按正确的顺序再次列出所有字段:

class MyForm(ModelForm):
    class Meta:
       model=Customer
       fields=[..., 'name', 'street', 'city', ...]

答案 1 :(得分:6)

在Django 1.9中,他们为Form类添加了新的参数 现在,您可以通过定义 field_order 来更改顺序 例如,添加两个字段以使用应用程序表单:

class SignupFormExtra(SignupForm):
    """
    A form to demonstrate how to add extra fields to the signup form, in this
    case adding the first and last name.
    """
    first_name = forms.CharField(label=_(u'First name'),
                             max_length=30,
                             required=False)

    last_name = forms.CharField(label=_(u'Last name'),
                            max_length=30,
                            required=False)
    field_order=['first_name','last_name']

您可以将它用于任何继承类表单的表单。

默认情况下,Form.field_order = None,它保留您在表单类中定义字段的顺序。如果field_order是字段名称列表,则按列表指定的顺序排序字段,并根据默认顺序追加其余字段。

答案 2 :(得分:5)

from django import forms

class CustomForm(forms.Form):
    ORDER = ('field1', 'field2', 'field3')
    def __init__(self, *args, **kwargs):
        super(CustomForm, self).__init__(*args, **kwargs)
        fields = OrderedDict()
        for key in self.ORDER:
            fields[key] = self.fields.pop(key)
        self.fields = fields

答案 3 :(得分:2)

当我们升级到Django 1.7时Skyjur使用.keyOrder停止工作(现在Django正在使用collections.OrderedDict)。因此,我必须找到解决办法,这似乎对我有用:

from collections import OrderedDict
...
class MyForm(forms
    def __init__(self, *args, **kwargs):
        fields = OrderedDict()
        for key in ("my_preferred_first_field", "my_preferred_second_field"):
            fields[key] = self.fields.pop(key)
        for key, value in self.fields.items():
            fields[key] = value
        self.fields = fields

答案 4 :(得分:1)

在较新的Django中,fields属性是collections.OrderedDict,自Python 3.2 has a new method move_to_end起,因此您可以简单地进行以下操作:

class CustomForm(forms.Form):

    ...

    # Note the following must contain all the fields in the form in the order
    # you desire.
    CUSTOM_ORDER = ('field1', 'field2', 'field3')

    def __init__(self, *args, **kwargs):
        super(CustomForm, self).__init__(*args, **kwargs)

        # Use custom order for form fields.
        for field_name in CUSTOM_ORDER:
            self.fields.move_to_end(field_name)