Django使用ccbv updateview预先填充表单字段,而不是模型的一部分

时间:2014-03-02 19:21:03

标签: django django-class-based-views django-forms updatemodel

我预先填充不属于模型的表单字段

 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])

表单如下:this

这里start_time不是模型的一部分,只有start_date。我使用了createview并使用datetime.combine将用户输入的时间和日期合并到一个日期时间,同时处理应用程序的时区。我现在做了相反的事情,从数据库中提取日期时间并将日期,时间组件放入单独的文件中。

我的第一个想法是在def get_object中进行并将其放在obj.start_time中,假设是否会填充表单,而不是正常工作。几点思考?

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)

1 个答案:

答案 0 :(得分:3)

您应该通过get_initial方法添加它,例如:

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
相关问题