Question

I'm to pre-populate a form field which is not part of the model

 class AppointmentInputForm(forms.ModelForm):
    start_date = forms.DateField(
        label='Date', required=True, input_formats=[DATE_FORMAT])
    start_time = forms.TimeField(
        label='Start Time', required=True, input_formats=[TIME_FORMAT])

The form looks like: this

Here start_time is not part of the model, only start_date is. I did the createview and use datetime.combine to combine both the user entered time and date to a single datetime while taken care of the timezone of the app. I now did to do the opposite, pull the datetime from the db and put the date, time components into separate fileds.

My first thought was do it in def get_object and put it in obj.start_time, assuming if would populate on the form, not working. Thoughs?

class AppointmentUpdateView(LoginRequiredMixin, UpdateView):
    ...
def get_object(self, queryset=None):
    ...
    obj = Appointment.objects.get(id=appointment_id)
    conv_date = obj.start_date.astimezone(time_zone)

    obj.start_time = conv_date.strftime(TIME_FORMAT)
Était-ce utile?

La solution

You should add it through the get_initial method, something like:

class AppointmentUpdateView(LoginRequiredMixin, UpdateView): 
    # ...

    def get_initial(self):
        initial = super(AppointmentUpdateView, self).get_initial()
        conv_date = self.get_object().start_date.astimezone(time_zone)
        initial["start_time"] = conv_date.strftime(TIME_FORMAT)
        return initial
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top