Django ModelForm小部件和非小部件字段排序

时间:2019-05-20 21:52:44

标签: django django-forms django-widget

我有一个带有时间(开始和结束)事件的Django(1.11.9)ModelForm。当我在模板中向用户显示它时,我希望last_field成为底部表单中的最后一个字段:

class EventForm(forms.ModelForm):
    dt = '%Y-%m-%d %H:%M'

    start = forms.DateTimeField(
        label="Start time (in event's local time)",
        required=False,
        input_formats=[dt]
    )

    end = forms.DateTimeField(
        label="End time (in event's local time)",
        required=False,
        input_formats=[dt]
    )

    class Meta:
        model = Event
        fields = [
         'name', 'flexibility', 'timezone', 
         'date_start', 'date_end', 'last_field', 
        ]

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

        self.fields['date_start'].widget = forms.HiddenInput()
        self.fields['date_end'].widget = forms.HiddenInput()

        i = kwargs.get('instance')
        tz = pytz.timezone(i.timezone) if i and i.timezone else None
        if i and i.flexibility == Event.FLEXIBILITY_ONTIME and tz:
            self.fields['start'].initial = i.date_start.astimezone(tz).strftime(self.dt) if i.date_start else None
            self.fields['end'].initial = i.date_end.astimezone(tz).strftime(self.dt) if i.date_end else None

        else:
            self.fields['start'].initial = None
            self.fields['end'].initial = None

但是,即使在'last_field'数组的末尾(根据文档https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#changing-the-order-of-fields)显式设置fields = [],也会在startend小部件字段中表单根据设置的字段顺序在其下方呈现。

是否有一种方法可以覆盖小部件以强制字段排序?谢谢

0 个答案:

没有答案