当前位置:  开发笔记 > 后端 > 正文

如何增加Django模板中显示的年份范围?

如何解决《如何增加Django模板中显示的年份范围?》经验,为你挑选了1个好方法。

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 %}

Join Now

{% csrf_token %} {{ form.as_p }}
{% endblock %}

在此输入图像描述



1> lennart..:

您可以将年份参数传递给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))

推荐阅读
手机用户2402851335
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有