How to use Date Picker in Django Template

In this article, We will discuss the date and time picker that you can use in a Django web project.

First, We will set up a JavaScript library for date picker in our HTML page and then will set up a custom widget and finally we will integrate date time picker with our Django app.

There can be many front end libraries available for datetime picker but in this tutorial we will use Tempus Dominus Bootstrap 4.

The key thing in our implementation is to assure Django will receive the correct format of date and time. And also reproduce the original format during the rendering of form. We will also use custom widgets to provide better integration with front end. So let’s start this tutorial by avoiding further introductory discussions.

Let us start with front end part od the date picker using:

Date Time Picker in Django Templates

Tempus Domain Bootstrap4
Docs Source-Code

This is a good JavaScript library integrated with Bootstrap4, But It requires moment.js and Bootstrap 4 and jQuery. To install this library you can use their CDN. In this site you have to copy CDN url and paste to your HTML page. It includes javascript, HTML , CSS

django date picker using bootstrap

To use this library you can use its CDN and put it into your HTML page. The snapshot given below is the static HTML for datepicker. (it is a basic datepicker without django implementation)

home.html

 <!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Static Example</title>
    <!-- Bootstrap 4 -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css"
        integrity="sha384-GJzZqFGwb1QTTN6wy59ffF1BuGJpLSa9DkKMp0DgiMDm4iYMj70gZWKYbI706tWS" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"
        integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"
        crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.6/umd/popper.min.js"
        integrity="sha384-wHAiFfRlMFy6i5SRaxvfOCifBUQy1xHdJ/yoi7FRNXMRBu5WHdZYu1hA6ZOblgut"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/js/bootstrap.min.js"
        integrity="sha384-B0UglyR+jN6CkvvICOB2joaf5I4l3gm9GU6Hc1og6Ls7i6U/mkkaduKaBhlAXv9k"
        crossorigin="anonymous"></script>
    <!-- Font Awesome -->
    <link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"
        integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
    <!-- Moment.js -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"
        integrity="sha256-VBLiveTKyUZMEzJd6z2mhfxIqz3ZATCuVMawPZGzIfA=" crossorigin="anonymous"></script>
    <!-- Tempus Dominus Bootstrap 4 -->
    <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/css/tempusdominus-bootstrap-4.min.css"
        integrity="sha256-XPTBwC3SBoWHSmKasAk01c08M6sIA5gF5+sRxqak2Qs=" crossorigin="anonymous" />
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.1.2/js/tempusdominus-bootstrap-4.min.js"
        integrity="sha256-z0oKYg6xiLq3yJGsp/LsY9XykbweQlHl42jHv2XTBz4=" crossorigin="anonymous"></script>
</head>

<body>
    <div class="input-group date" id="datetimepicker1" data-target-input="nearest">
        <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1" />
        <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
            <div class="input-group-text"><i class="fa fa-calendar"></i></div>
        </div>
    </div>
    <script>
        $(function () {
            $("#datetimepicker1").datetimepicker();
        });
    </script>
</body>

</html>

Now let’s make integration of this HTML Datepicker input with a Django form. To do this make a forms.py file inside your project folder.

Forms.py

from django import forms
class DateForm(forms.Form):
    date=forms.DateTimeField(
        input_formats=['%d/%m/%Y %H:%M'],
        widget=forms.DateTimeInput(attrs={
            'class': 'form-control datetimepicker-input',
            'data-target': '#datetimepicker1'
        })
    ) 

Template (HTML file)

<div class="input-group date" id="datetimepicker1" data-target-input="nearest">
    <!-- <input type="text" class="form-control datetimepicker-input" data-target="#datetimepicker1"/> -->
    {{ form.date}}
    <div class="input-group-append" data-target="#datetimepicker1" data-toggle="datetimepicker">
        <div class="input-group-text"><i class="fa fa-calendar"></i></div>
    </div>
</div>
<script>
    $(function () {
        $("#datetimepicker1").datetimepicker({
            format: 'DD/MM/YYYY HH:mm',
        });
    });
</script>

Now we will make widget inside our app.

datepicker/views.py

from django.shortcuts import render
from django.http import HttpResponse
from .forms import DateForm
# Create your views here.
def home(request):
    context={}
    context['form']= DateForm
    return render(request,'datepicker\home.html',context) 

Urls.py

from django.contrib import admin
from django.urls import path
from datepicker import views
urlpatterns = [
    path('admin/', admin.site.urls),
    path('',views.home),
] 

That’s it now run the server on localhost by giving command “python manage.py runserver” in your project directory.

Date Picker for Django Using Custom Widget

 We can make custom widget using below code:

Datepicker\widget.py

from django.forms import DateTimeInput
class BootstrapDateTimePickerInput(DateTimeInput):
    template_name = 'widgets/bootstrap_datetimepicker.html'
    def get_context(self, name, value, attrs):
        datetimepicker_id = 'datetimepicker_{name}'.format(name=name)
        if attrs is None:
            attrs = dict()
        attrs['data-target'] = '#{id}'.format(id=datetimepicker_id)
        attrs['class'] = 'form-control datetimepicker-input'
        context = super().get_context(name, value, attrs)
        context['widget']['datetimepicker_id'] = datetimepicker_id
        return context 

Datepicker/home.html

{% include "django/forms/widgets/input.html" %}
<div class="input-group-append" data-target="#{{ widget.datetimepicker_id }}" data-toggle="datetimepicker">
    <div class="input-group-text"><i class="fa fa-calendar"></i></div>
</div>
</div>
<script>
    $(function () {
        $("#{{ widget.datetimepicker_id }}").datetimepicker({
            format: 'DD/MM/YYYY HH:mm',
        });
    });
</script>

datepicker/forms.py

from .widgets import BootstrapDateTimePickerInput
class DateForm(forms.Form):
    date = forms.DateTimeField(
        input_formats=['%d/%m/%Y %H:%M'], 
        widget=BootstrapDateTimePickerInput()
    ) 

Now render the form using a template tag {{ form. date}} inside HTML files. And it’s done.