14

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?

Mikhail Korobov
  • 21,908
  • 8
  • 73
  • 65
Herman Schaaf
  • 46,821
  • 21
  • 100
  • 139
  • I don't see what the problem is: extract your two dates, and store them in the model. – Marcin Feb 18 '12 at 11:07
  • @marcin: How do I set the `initial` value to the value of the two model fields in a way that makes sense and doesn't hack the __init__ function of the form? Am I just missing something obvious? – Herman Schaaf Feb 18 '12 at 11:12
  • what's wrong with setting the `initial` parameter to each field? – Marcin Feb 18 '12 at 12:11
  • @Marcin: Just not a pleasing solution, as it puts a crucial part of form logic into the view. Alternatively, can override the form `__init__` function to do it, but still not the best. I thought there might be a cleaner solution, but I suppose the answer is to just go with the ugly solution and move on. – Herman Schaaf Feb 18 '12 at 12:20
  • In what way does it put form logic into the view? Are you using a modelform? If not, and there is a good reason why you wouldn't, turn your form into a modelform manque, with a reference to the target model object. – Marcin Feb 18 '12 at 12:23
  • This is old thing, but google suggested for me to look into this: https://coderwall.com/p/kq1d5a/handling-multiple-input-values-for-single-django-form-field It's a workaround but it kinda works i guess.. – Nebulosar Feb 07 '18 at 13:59

1 Answers1

10

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.

Mikhail Korobov
  • 21,908
  • 8
  • 73
  • 65