在signUp
我创建的形式中,我预先填充date-of-birth field
到"昨天".但是这一scroll down menu
年仅限于9年.我怎样才能增加出现的年数.它不能受到限制.我附上了图片.你可以看到这option to choose
九年中只有一个.任何想法如何解决这一问题?
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 %}{% endblock %}Join Now
您可以将年份参数传递给SelectDateWidget,如下所示:
SelectDateWidget(years=range(1900, 2100))
虽然这不会接受无限范围,但在大多数情况下应该这样做.
文档,您还可以在开发版本中添加月限制:)
如果您想动态更改范围,可以执行与此类似的操作:
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))