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?
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.
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.
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.
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() }
There's no need to subclass DateInput
.
class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' widgets = { 'my_date': DateInput(attrs={'type': 'date'}) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With