2016-07-29 75 views
-1

我正在使用用於存儲學生數據的表單。當我嘗試渲染表單時,它會生成文本輸入而不是數據。Django - 在模板中呈現日期字段

我如何使用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}} 

回答

1

默認情況下,Django將顯示TextInput場,你可以重寫你的形式顯示DateField渲染日期輸入..

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

class StudentRegisterForm(ModelForm): 
    class Meta: 
     model = StudentRegister 
     fields = '__all__' 
     widgets = { 
      'dob': DateInput() 
     } 
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)) 
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)) 
前面的回覆小幅盤整