0

I have a django (1.11.9) ModelForm for events with times (start and end). When I display it to the user in a template I want last_field to be the last field in the form at the bottom:

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

however, even explicitly setting 'last_field' at the end of the fields = [] array (per docs https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#changing-the-order-of-fields), the start and end widget fields in the form render below it out of the set field order.

is there a way to override the widgets to force the ordering of the fields? thanks

Chris B.
  • 1,505
  • 5
  • 26
  • 48
  • It's not a perfect solution, but have you tried defining the `last_field` explicitly after `end` on EventForm? – schillingt May 21 '19 at 02:06
  • re-ordering the model fields doesn't change it `start` (`date_start`) and `end` (`date_end`) still render last in the form and i'm unclear what's forcing the widgets to the end of the form (or how to over ride that ordering). – Chris B. May 21 '19 at 13:54
  • You'd have to add some breakpoints in Django to see how the forms work. Otherwise your best bet is to customize the template itself. – schillingt May 21 '19 at 13:56

0 Answers0