How to Use Bootstrap Datepicker, Timepicker and Datetimepicker in Django

Bootstrap Datepicker and Datetimepicker are handy tools for enhancing date and time input fields in your Django forms. They provide user-friendly date and time selection widgets. In this tutorial, we’ll walk through the steps to integrate Bootstrap Datepicker and Datetimepicker into your Django project, complete with practical examples.

Read our Blog on How to Integrate and Use Bootstrap 5 in Django

Prerequisites

Before we begin, ensure you have the following prerequisites in place:

  1. Django Installed: You should have Django installed on your system. You can install it using pip:
   pip install django
  1. Bootstrap and jQuery: Make sure you have included Bootstrap and jQuery in your project. You can either download and include them in your project manually or use a Content Delivery Network (CDN) in your HTML template.
  2. Basic Django Project: You should have a basic Django project set up. If you haven’t created one yet, you can do so by running:
   django-admin startproject myproject

Replace myproject with your project’s name.

Step 1: Create a Django App

Let’s start by creating a Django app within your project. Run the following command:

python manage.py startapp myapp

Now, add the newly created app, myapp, to your project’s INSTALLED_APPS in the settings.py file.

# myproject/settings.py

INSTALLED_APPS = [
    # ...
    'myapp',
    # ...
]

Step 2: Create a Model

In this example, we’ll create a simple model to represent events with date and time fields. Open myapp/models.py and define the model as follows:

from django.db import models

class Event(models.Model):
    name = models.CharField(max_length=100)
    date = models.DateField()
    time = models.TimeField()
    datetime = models.DateTimeField()

Don’t forget to run migrations to create the database table for this model:

python manage.py makemigrations
python manage.py migrate

Step 3: Create a Form

Now, create a form for the Event model. In myapp/forms.py, add the following code:

from django import forms
from .models import Event

class EventForm(forms.ModelForm):
    class Meta:
        model = Event
        fields = ['name', 'date', 'time', 'datetime']
        widgets = {
            'date': forms.DateInput(attrs={'class': 'datepicker'}),
            'time': forms.TimeInput(attrs={'class': 'timepicker'}),
            'datetime': forms.TextInput(attrs={'class': 'datetimepicker'}),
        }

In the EventForm class, we specify the widgets attribute for the date, time, and datetime fields, assigning CSS classes datepicker, timepicker, and datetimepicker to each field, respectively. These classes will be used to initialize the Bootstrap Datepicker and Datetimepicker.

Step 4: Create a Template

Create an HTML template for your form. Inside the myapp directory, create a folder named templates if it doesn’t already exist, and within it, create a new HTML file, e.g., event_form.html. In this file, you can use the following code:

{% extends 'base.html' %}

{% block content %}
  <h2>Create an Event</h2>
  <form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-primary">Save</button>
  </form>
  <script>
    $(document).ready(function() {
      $('.datepicker').datepicker({
        format: 'yyyy-mm-dd',
        autoclose: true,
      });

      $('.timepicker').timepicker({
        format: 'hh:ii:ss',
        autoclose: true,
        showMeridian: false,
      });

      $('.datetimepicker').datetimepicker({
        format: 'YYYY-MM-DD HH:mm:ss',
        showClear: true
      });
    });
  </script>
{% endblock %}

Here, we’re extending a base template (base.html) and rendering the form fields using {{ form.as_p }}. Additionally, we include a script at the end to initialize the Bootstrap Datepicker, Timepicker, and Datetimepicker for the respective fields with the classes datepicker, timepicker, and datetimepicker.

Here’s an example of a base.html file that you can use as a template for your Django project, which includes the necessary CSS and JavaScript libraries for Bootstrap Datepicker, Timepicker, and Datetimepicker:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>{% block title %}My Website{% endblock %}</title>
    <!-- Include Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <!-- Include jQuery (required for Bootstrap JavaScript plugins) -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <!-- Include Bootstrap JavaScript -->
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
    <!-- Include Bootstrap Datepicker CSS and JS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
    <!-- Include Bootstrap Timepicker CSS and JS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/css/bootstrap-timepicker.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-timepicker/0.5.2/js/bootstrap-timepicker.min.js"></script>
    <!-- Include Bootstrap Datetimepicker CSS and JS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
</head>
<body>

    <div class="container mt-5">
        {% block content %}
        <!-- Content goes here -->
        {% endblock %}
    </div>

    <!-- Custom JavaScript (if needed) -->
    {% block javascript %}{% endblock %}
</body>
</html>

Step 5: Create Views and URLs

In myapp/views.py, create views for rendering the form and handling form submissions:

from django.shortcuts import render, redirect
from .forms import EventForm

def create_event(request):
    if request.method == 'POST':
        form = EventForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('event_list')  # Replace 'event_list' with your desired redirect URL after successful form submission
    else:
        form = EventForm()
    return render(request, 'event_form.html', {'form': form})

Additionally, you can create a view to display a list of events, but that’s beyond the scope of this example.

Next, define URL patterns in myapp/urls.py to route requests to these views:

from django.urls import path
from . import views

urlpatterns = [
    path('create_event/', views.create_event, name='create_event'),
    # Define other URLs as needed
]

Step 6: Include URLs in Project’s URLs

In your project’s urls.py (located in the main project directory), include the URLs of your app like this:

from django.contrib import admin
from django.urls import include, path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('myapp/', include('myapp.urls')),
]

Step 7: Run the Development Server

Finally, start the development server:

python manage.py runserver

Visit http://127.0.0.1:8000/myapp/create_event/ in your web browser to see the form with the Bootstrap Datepicker, Timepicker, and Datetimepicker in action.

Congratulations! You’ve successfully integrated Bootstrap Datepicker and Datetimepicker into your Django project, allowing users to input dates, times, and datetimes with ease. Customize the format, options, and icons as needed to match your projact’s requirements and styling preferences.

Find this tutorial on Github.

Blogs You Might Like to Read!