Question

I have the following form in Django 1.6:

class TestForm(forms.form):
    first_date = forms.DateField(widget=SelectDateWidget(), required=True) 
    name = forms.CharField(widget=forms.PasswordInput(), label="Real Name")

I want to create an instance of this form in my view using a dictionary (bear with me, I HAVE to use a python dictionary here).

Reading the documentation I found an example without DateField and tested it:

form = TestFormNoDateField({"username": "John", "hair_color": "Black")

This worked like a charm. The problem is when I try the same method using a form with DateField:

form = TestForm("name": "John", "first_date": "2005-01-23")

This raises a Value Error at xxx: Too many values to unpack.

How should I format the date field to avoid this error?

Was it helpful?

Solution

Pass a datetime.date in the first_date value:

form = TestForm("name": "John", 
                "first_date": datetime.date(year=2005, month=1, day=23)})

Or, if you have a date string, convert it to datetime by using strprime():

form = TestForm("name": "John", 
                "first_date": datetime.datetime.strptime('2005-01-23', '%Y-%m-%d')})

Don't forget to import datetime.

Hope that helps.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top