Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to represent two model fields as one form field in Django?

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?

like image 244
Herman Schaaf Avatar asked Feb 17 '12 18:02

Herman Schaaf


1 Answers

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.

like image 184
Mikhail Korobov Avatar answered Sep 20 '22 14:09

Mikhail Korobov