且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Django中将两个模型字段表示为一个表单字段?

更新时间:2022-12-11 14:11:13

似乎在django中使用当前的小部件API是不可能的。这张票是最古老的django门票之一,年龄为7岁: https://code.djangoproject.com /票/ 27



您可以从模型表单中排除原始的2个字段,创建一个新字段并覆盖表单的保存方法。


I can't seem to figure out how to handle the following situation properly in Django:

I have a date range in a model, which I store as two separate fields, date_start and date_end:

start_date = models.DateTimeField()
end_date = models.DateTimeField()

In the form for this model, I want to represent this as one field, with one label:

timespan = forms.Field(widget=widgets.SelectDateRangeWidget(), label="Date Range")

As it is now, I extended MultiWidget to create the SelectDateRangeWidget:

class SelectDateRangeWidget(forms.MultiWidget):
    ...

Which then incorporates two Date widgets. I want to use this, but then clean it into two separate model fields, and also preserve the ability to load initial data into the form field. Is the only way to manually set initial to the value of those two fields every time, maybe in the __init__ function of the form, and also manually clean it into those two model fields, or is there a cleaner (so to speak) way to do this?

It seems it is not possible in django using current widgets API. The ticket is one of the oldest django tickets, it is 7 years old: https://code.djangoproject.com/ticket/27 .

You may exclude original 2 fields from the model form, create a new field and override form's save method.