I want to implement a django form with datepicker. I made my forms.py
from django import forms
class DateRangeForm(forms.Form):
start_d
The example below uses Django's generic.CreateView:
models.py file
class Task(models.Model):
task_due_date = models.DateField()
views.py file
from bootstrap_datepicker_plus import DatePickerInput
class add_task(LoginRequiredMixin,generic.CreateView):
model = Task
fields = '__all__'
def get_form(self):
form = super().get_form()
form.fields['task_due_date'].widget = DatePickerInput()
return form
template_name = 'team/add_task.html'
templates/add_task.html
{% extends 'base.html' %}
{% load bootstrap4 %}
{% block body %}
{% bootstrap_javascript jquery='full' %}
{{ form.media }}
<h1>Add a Task</h1>
<br>
<div class="container">
<div class="row">
<form method="POST" action="{% url 'team:add_task' %}" id="taskForm">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button type="submit" class="btn btn-primary btn-large">Add</button>
{% endbuttons %}
</form>
</div>
</div>
{% endblock %}
With the end result being:
Show end result
You can use forms.DateInput()
widget, instead of forms.TextInput()
:
from functools import partial
DateInput = partial(forms.DateInput, {'class': 'datepicker'})
class DateRangeForm(forms.Form):
start_date = forms.DateField(widget=DateInput())
end_date = forms.DateField(widget=DateInput())
To make JQuery Datepicker work, you have to initialise it:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function() {
$('.datepicker').datepicker();
});
</script>