如何在Django模板中增加几年的范围? [英] how to increase the range of years to show up in Django templates?
问题描述
在我创建的 signUp
表单中,我将出生日期字段
预先填充昨天。
但$ 下拉菜单
为年限制9年。如何增加出现的年数?不能限制我附上了形象。您可以看到,只有在这九年之内有一个选项来选择
。任何想法如何解决这个问题?
注册/ forms.py:
from django import forms
from signups.models import SignUp
import datetime
from django.forms.extras.widgets import SelectDateWidget
def昨天():
昨天=(datetime.date.today() - datetime.timedelta(1))
返回昨天
class SignUpForm (forms.ModelForm):
date_of_birth = forms.DateField(widget = SelectDateWidget(),initial = yesterday)
class Meta:
model = SignUp
注册/ models.py:
来自django.db导入模型
从django.utils.encoding导入smart_unicode
从blogapp.models导入的$ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $
class SignUp(models.Model):
#null在数据库
first_name = models.CharField(max_length = 100,null = True,blank = True)
last_name = models.CharField max_length = 100,null = True,blank = True)
#defau lt = null = false,blank = false,电子邮件是必需的
email = models.EmailField(unique = True)
#when创建时间戳但不更新时
timeStamp = models.DateTimeField auto_now_add = True,auto_now = False)
已更新= 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: code>
def signup_view(request):
form = SignUpForm(request.POST或None)
如果form.is_valid():
save_it = form.save(commit = False)
save_it.save()
messages.success(请求,谢谢你注册 )
return HttpResponseRedirect(/ accounts / register_success)
els e:
args = {}
args ['form'] = form
return render(request,signup.html,args)
templates / signup.html:
{%extendsbase.html%}
{%block content%}
< h2>现在加入< / h2>
< form action =method =post> {%csrf_token%}
{{form.as_p}}
<输入类型=submitvalue =register/>
< / form>
{%endblock%}
SelectDateWidget如下:
SelectDateWidget(years = range(1900,21))
虽然这不会接受无限范围,但在大多数情况下应该做。
一个href =https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.extras.widgets.SelectDateWidget =nofollow>文档,你也可以在开发版本中添加月份限制:)
如果您想随时间动态更改范围,您可以执行类似的操作:
from datetime import datetime
##范围将是当前年份
##与未来最远的一年之间的差额或过去你会想包括。
date_range = 100
this_year = datetime.now()。year
### django code here ###
SelectDateWidget(years = range(this_year - date_range ,this_year + date_range))
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 %}
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))
这篇关于如何在Django模板中增加几年的范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!