Reputation: 607
I have a SelectDateWidget in a Django form that should only allow users to select dates from a certain number of years ago. How do I limit the months and days in the widget? For example, a user born in the last possible year should not be able to select January 1 when the current date is January 28. Similarly, someone born in the most recent possible year should not be allowed to select February 1 when the current date is January 28.
Here is my form:
class Form(forms.Form):
birthday = forms.DateField(widget=SelectDateWidget(empty_label=('Year', 'Month', 'Day'), years=range(datetime.date.today().year-22, datetime.date.today().year - 15)))
How do I set the months and days allowed in the form?
Upvotes: 0
Views: 1527
Reputation: 25539
I'm not sure what are the rules for your widget, but you could always use form constructor to create the field dynamically:
class FooForm(forms.Form):
def __init__(self, *args, **kwargs):
user = kwargs.pop('user', None)
super(FooForm, self).__init__(*args, **kwargs)
if user:
# calculate the list of years based on user's information and the rules you have
# e.g. years = range(2010, 2016)
self.fields['birthday'] = forms.DateField(widget=SelectDateWidget(empty_label=('Year', 'Month', 'Day'),
years=years))
Then in your views you do:
def views(request):
form = FooForm(request.POST or None, user=request.user)
Upvotes: 2