aldesabido aldesabido - 14 days ago 5
Python Question

Django DateRangeField issue

I have a problem with DateRangeField inserting to database using Forms.

model.py

from django.contrib.postgres.fields import DateRangeField
from django.db import models

class Event(models.Model):
name = models.CharField(max_length=200)
datefromto = DateRangeField()


views.py

date_from = '2011-01-01'
date_to = '2011-01-31'
data = {
"name" : "Test Name",
"datefromto" : [date_from,date_to ]
}

form = Event_form(data)
if form.is_valid():
form.save()
else:
print(form.errors)


forms.py

class Event_form(forms.ModelForm):
class Meta:
model = Event
fields = ('name','datefromto')

def clean(self):
print(self.cleaned_data)
#{"name" : "Test Name"} there should be 'datefromto' key


When I call the form.is_valid() it returns "datefromto is required" it shouldn't be like this because there's a 'datefromto' inside the dictionary. When I try to print the cleaned_data in form clean function, it only prints {"name" : "Test Name"} without the datefromto key.




Django 1.9,Python 2.7 and Postgre 9.3.14.

Answer

After digging into the django source code, you should append number suffix for range field like that:

date_from = '2011-01-01'
date_to = '2011-01-31'
data = {
    "name" : "Test Name",
    "datefromto_0" : date_from,
    "datefromto_1" : date_to
}

form = Event_form(data)
if form.is_valid():
    form.save()
else:
    print(form.errors)

I have used pdb to trace the code inside django, and found this trick...

And when you get stuck with other the issues in django next time, you can make use of pdb to trace. it is really a great tool for python debugging...

hope it would help... :).