问题
In the signUp
form I am creating, I am pre-populating the date-of-birth field
to "yesterday".
But the scroll down menu
for year is limited to 9 years. how can I increase the number of years to show up. It must not be limited. I have attached the image. you can see that there is an option to choose
only among those nine years. Any ideas how to fix this?
signups/forms.py:
from django import forms
from signups.models import SignUp
import datetime
from django.forms.extras.widgets import SelectDateWidget
def yesterday():
yesterday = (datetime.date.today() - datetime.timedelta(1))
return yesterday
class SignUpForm(forms.ModelForm):
date_of_birth = forms.DateField(widget=SelectDateWidget(), initial=yesterday)
class Meta:
model=SignUp
signups/models.py:
from django.db import models
from django.utils.encoding import smart_unicode
from blogapp.models import Post
class SignUp(models.Model):
#null in database
first_name=models.CharField(max_length=100,null=True,blank=True)
last_name=models.CharField(max_length=100,null=True,blank=True)
#default is null=false, blank=false, email is necessary
email=models.EmailField(unique=True)
#when created make timestamp but not when updated
timeStamp=models.DateTimeField(auto_now_add=True,auto_now=False)
updated=models.DateTimeField(auto_now_add=False,auto_now=True)
is_active=models.BooleanField()
date_of_birth=models.DateTimeField()
myPosts=models.ManyToManyField(Post)
def __unicode__(self):
return smart_unicode(self.email,encoding='utf-8',strings_only=False,errors='strict')
signup/views.py:
def signup_view(request):
form=SignUpForm(request.POST or None)
if form.is_valid():
save_it=form.save(commit=False)
save_it.save()
messages.success(request, "Thank you for signing up")
return HttpResponseRedirect("/accounts/register_success")
else:
args={}
args['form']=form
return render(request,"signup.html",args)
templates/signup.html:
{% extends "base.html" %}
{% block content %}
<h2>Join Now</h2>
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="register"/>
</form>
{% endblock %}

回答1:
You can pass a years argument into SelectDateWidget as follows:
SelectDateWidget(years=range(1900, 2100))
Although this will not accept an infinite range, under most circumstances it should do.
Documentation, you can also add month restraints in the development version :)
If you wanted to dynamically change the range with time, you could do something similar to this:
from datetime import datetime
## range would be the difference between the current year,
## and the farthest year into the future or past you would want to include.
date_range = 100
this_year = datetime.now().year
### django code here ###
SelectDateWidget(years=range(this_year - date_range, this_year + date_range))
来源:https://stackoverflow.com/questions/22492647/how-to-increase-the-range-of-years-to-show-up-in-django-templates