Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django form.as_p DateField not showing input type as date

Tags:

Working on my first django app, and I have a model defined with some DateFields, and then a ModelForm off of that model i.e.

models.py

class MyModel(models.Model):     ...     my_date = models.DateField('my date')     ...  class MyModelForm(ModelForm):     class Meta:         model = MyModel         fields = '__all__' 

views.py

def show(request):     form = MyModelForm     template_name = 'myapp/show.html'     return render(request,template_name,{'form':form}) 

and then in my html I use the .as_p to have django render the form for me

<form action="/show/" method="post">{% csrf_token %} {{ form.as_p }} <input type="submit" value="Submit" /> </form> 

But the DateFields have input type text, not date. Is there a way to change this?

like image 954
C.B. Avatar asked Apr 03 '14 18:04

C.B.


People also ask

What does {{ form AS_P }} do?

as_p() [Django-doc] is a method on a Form . It produces a SafeText object [Django-doc] that contains HTML code to be included in the template.

What is form Is_valid () in Django?

The is_valid() method is used to perform validation for each field of the form, it is defined in Django Form class. It returns True if data is valid and place all data into a cleaned_data attribute.

What is Django datetime format?

DateTimeField in Django Forms is a date field, for taking input of date and time from user. The default widget for this input is DateTimeInput. It Normalizes to: A Python datetime. datetime object.


2 Answers

You can create a custom widget:

from django import forms  class DateInput(forms.DateInput):     input_type = 'date'  class MyModelForm(forms.ModelForm):     class Meta:         model = MyModel         fields = '__all__'         widgets = {             'my_date': DateInput()         } 
like image 143
laidibug Avatar answered Sep 22 '22 03:09

laidibug


There's no need to subclass DateInput.

class MyModelForm(forms.ModelForm):     class Meta:         model = MyModel         fields = '__all__'         widgets = {             'my_date': DateInput(attrs={'type': 'date'})         } 
like image 26
jhrr Avatar answered Sep 21 '22 03:09

jhrr