I want to implement a django form with datepicker. I made my forms.py
from django import forms
class DateRangeForm(forms.Form):
start_date = forms.DateField(widget=forms.TextInput(attrs=
{
'class':'datepicker'
}))
end_date = forms.DateField(widget=forms.TextInput(attrs=
{
'class':'datepicker'
}))
and views.py
if request.method == "POST":
f = DateRangeForm(request.POST)
if f.is_valid():
c = f.save(commit = False)
c.end_date = timezone.now()
c.save()
else:
f = DateRangeForm()
args = {}
args.update(csrf(request))
args['form'] = f
return render(request, 'trial_balance.html', {
'form': f
})
balance.html
<div>
<form action="" method="POST"> {% csrf_token %}
Start Date:{{ form.start_date }} End Date:{{ form.end_date }}<br/>
<input type = "submit" name = "submit" value = "See Results">
</form>
</div>
And still there is no datepicker in my input box of that form. I also tried with including my files link in the script as in my balance.html
<script src="{{ STATIC_URL }}js/jquery-1.3.2.min.js"></script>
still the datepicker is not working. But when including jquery in my html file, it also makes not to work jquery-treetable which I have implemented in my html file.
How to make the datepicker work ?
Android provides controls for the user to pick a time or pick a date as ready-to-use dialogs. Each picker provides controls for selecting each part of the time (hour, minute, AM/PM) or date (month, day, year).
Use a calendar picker (single or range) when the user needs to know a date's relationship to other days or when a date could be variable. The user can view and pick dates from a calendar widget or manually type them in the text field. Use when asking the user to input a specific time.
To customize the format a DateField in a form uses we can set the input_formats kwarg [Django docs] on the field which is a list of formats that would be used to parse the date input from the user and set the format kwarg [Django docs] on the widget which is the format the initial value for the field is displayed in.
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>
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