我正在尝试在 Django ModelForm 表单中设置
DateTimeRangeField
,但收到验证错误“此字段为必填字段”。 Django 似乎既不识别 psycopg2.extras.DateTimeTZRange
实例,也不识别任何日期字符串作为有效值。
如何设置
DateTimeRangeField
的值?
条纹示例:
# 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())
输出:
{'range': [ValidationError(['This field is required.'])]}
您通过以下方式传递数据:
form = ReservationForm(
data={
'range_0': '2024-04-21 10:00',
'range_1': '2024-04-21 10:00',
}
)