Django form field using SelectDateWidget

2020-06-04 04:43发布

I've installed the latest SVN branch from Django which includes the new forms. I'm trying to use the SelectDateWidget from django.forms.extras.widgets but the field is showing up as a normal DateInput widget.

Here is the forms.py from my application:

from django import forms
from jacob_forms.models import Client

class ClientForm(forms.ModelForm):
    DOB = forms.DateField(widget=forms.extras.widgets.SelectDateWidget)

    class Meta:
            model = Client

What am I doing wrong? Checking the forms/extras/widgets.py I see the SelectDateWidget class exists.

5条回答
【Aperson】
2楼-- · 2020-06-04 05:21

Here is the form.py

from django import forms
from django.forms import extras

DOY = ('1980', '1981', '1982', '1983', '1984', '1985', '1986', '1987',
       '1988', '1989', '1990', '1991', '1992', '1993', '1994', '1995',
       '1996', '1997', '1998', '1999', '2000', '2001', '2002', '2003',
       '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011',
       '2012', '2013', '2014', '2015')


DOB = forms.DateField(widget=extras.SelectDateWidget(years = DOY))
查看更多
Evening l夕情丶
3楼-- · 2020-06-04 05:25

From the ticket re: the lack of documentation for SelectDateWidget here: Ticket #7437

It looks like you need to use it like this:

widget=forms.extras.widgets.SelectDateWidget()

Note the parentheses is the example.

查看更多
叛逆
4楼-- · 2020-06-04 05:26

Your code works fine for me as written. In a case like this, check for mismatches between the name of the field in the model and form (DOB versus dob is an easy typo to make), and that you've instantiated the right form in your view, and passed it to the template.

查看更多
爱情/是我丢掉的垃圾
5楼-- · 2020-06-04 05:36

The real problem was that SelectDateWidget can't be referenced this way. Changing the code to reference it differently solved my problem:

from django.forms import extras
...
    DOB = forms.DateField(widget=extras.SelectDateWidget)

This seems to be a limitation that you can't reference package.package.Class from an imported package. The solution imports extras so the reference is just package.Class.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-06-04 05:41

Why not use forms.SelectDateWidget. Just use it as reference.

import datetime

from django import forms


class HistDateForm(forms.Form):
    cur_year = datetime.datetime.today().year
    year_range = tuple([i for i in range(cur_year - 2, cur_year + 2)])
    hist_date = forms.DateField(initial=datetime.date.today() - datetime.timedelta(days=7),widget=forms.SelectDateWidget(years=year_range))
查看更多
登录 后发表回答