Django - 在模板中呈现日期字段

时间:2016-07-29 18:10:28

标签: django django-forms django-templates

我正在处理一个用于存储学生数据的表单。当我尝试渲染表单时,它会生成文本输入而不是数据。

如何使用django

渲染日期输入

forms.py

class StudentRegister(forms.Form):

firstname = forms.CharField(max_length= 50)
lastname = forms.CharField(max_length = 50, required=False)
mail = forms.EmailField(required=False)
dob = forms.DateField()

HTML

{{form.dob}}
{{form.dob.error}}

3 个答案:

答案 0 :(得分:2)

默认情况下,Django会显示TextInput字段,您可以覆盖表单以显示DateField ..

class DateInput(forms.DateInput):
    input_type = 'date'

class StudentRegisterForm(ModelForm):
    class Meta:
        model = StudentRegister
        fields = '__all__'
        widgets = {
            'dob': DateInput()
        }

答案 1 :(得分:0)

使用SelectDateWidget

from django.forms import SelectDateWidget
# from django.forms.extras.widgets Django < 1.9
from django.utils import timezone

def past_years(ago):
    this_year = timezone.now().year
    return list(range(this_year, this_year - ago - 1))

class StudentRegisterForm(forms.Form):
    ...
    dob = DateField(widget=SelectDateWidget(years=past_years(100))

答案 2 :(得分:0)

弗拉基米尔·达尼洛夫先前的回复只是一个小小的修正

from django.forms import SelectDateWidget
# from django.forms.extras.widgets Django < 1.9
from django.utils import timezone

def past_years(ago):
    this_year = timezone.now().year
    return list(range(this_year-ago-1, this_year)) #<------- Parameters should be inverted here

class StudentRegisterForm(forms.Form):
    dob = DateField(widget=SelectDateWidget(years=past_years(100))