Search code examples
djangodjango-formspsycopg2

Setting DateTimeRangeField programmatically via a ModelForm


I'm trying to set the DateTimeRangeField in a Django ModelForm form, but I'm getting a validation error "this field is required". It seems that Django is not recognizing nor psycopg2.extras.DateTimeTZRange instance, nor any date strings as a valid value.

How can I set the value of DateTimeRangeField?

Striped down example:

# models.py
from django.contrib.postgres.fields import DateTimeRangeField

class Reservation(models.Model):
    range = DateTimeRangeField()

# forms.py
class ReservationForm(forms.ModelForm):
    class Meta:
        model = Reservation
        exclude = []

# test.py
from psycopg2.extras import DateTimeTZRange

form = ReservationForm(data={
    'range': DateTimeTZRange(
        lower='2024-04-21 10:00',
        upper='2024-04-21 11:00'
    )
})

if form.is_valid():
    form.save()
else:
    print(form.errors.as_data())

Output: {'range': [ValidationError(['This field is required.'])]}


Solution

  • You pass the data with:

    form = ReservationForm(
        data={
            'range_0': '2024-04-21 10:00',
            'range_1': '2024-04-21 10:00',
        }
    )

    A RangeWidget uses subwidgets to render the from and to. These are suffixed with the "index", and thus in this case range_0 and range_1.