2👍
Assumption: you’re just letting Django render the field as-is in the template.
Django itself doesn’t provide a date-picker widget, and as you’ve found the ‘widget’ used by Django to represent a DateTimeField is a simple text field.
To have this render with a datepicker widget, you have a three options:
(jump straight to the 3rd if you just want a solution)
Pass a type
of datetime-local
to the widget inbuilt Django widget
(Not the recommended approach)
You can pass a type
to the widget in order to have it provide a specific field type rendered in the browser.
e.g
from django.forms.widgets import DateTimeWidget
class MyCommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['title', 'text', 'notes', 'date']
widgets = {
'date': DateTimeInput(attrs={'type': 'datetime-local'}),
}
This will cause the field to have the datetime-local
type and some browsers will render a widget for entering date and time.
An important note when doing this is that the date format for the value
of the field (as it will be rendered in the template) is important. It must be RFC 3339-formatted (e.g. 2001-10-08T22:47:31-07:00 – there is an RFC 3339 package in PyPI at https://pypi.python.org/pypi/rfc3339/)
Use a client-side datetime picker
Browser support for native datetime widgets is poor and getting the output of Django to match the required value for the datetime-local
field is annoying.
Fortunately, there are quite a few javascript libraries out there for providing date pickers (bootstrap has one, there are things like Flatpickr)
Use a Django addon that includes a date widget
There are addons (such as django-datetime-widget and django-bootstrap3-datetimepicker) that allow you to add a widget in the Django form using a Python class, and then that will render a Javascript-based widget in the client side.
If you can find an addon that you’re happy with (i.e. it provides a date/time picker you like) then this is certainly the option I would recommend – mainly because the addon should take care of making sure the output from Django is in a format that the Javascript-based picker can handle, and the result in the field is something Django can handle.
I should note: I haven’t personally used any of these date-time pickers.