31๐
You can also simply use Jquery in your templates. The jquery DateTime Picker allows each customization.
109๐
Following is what I do, no external dependencies at all.:
models.py:
from django.db import models
class Promise(models):
title = models.CharField(max_length=300)
description = models.TextField(blank=True)
made_on = models.DateField()
forms.py:
from django import forms
from django.forms import ModelForm
from .models import Promise
class DateInput(forms.DateInput):
input_type = 'date'
class PromiseForm(ModelForm):
class Meta:
model = Promise
fields = ['title', 'description', 'made_on']
widgets = {
'made_on': DateInput(),
}
my view:
class PromiseCreateView(CreateView):
model = Promise
form_class = PromiseForm
And my template:
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create" />
</form>
The date picker looks like this:
- [Django]-How do I use the built in password reset/change views with my own templates
- [Django]-Specifying a mySQL ENUM in a Django model
- [Django]-AssertionError: database connection isn't set to UTC
77๐
Djangoโs TextInput widget (and all of its subclasses) support specifying a type attribute to set the type of form.
You can use this to set the input type to date
(W3C specification), for example in the following way :
date = fields.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'}))
To apply this on a forms.ModelForm:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ['my_field', 'date']
widgets = {
'date': forms.widgets.DateInput(attrs={'type': 'date'})
}
- [Django]-How can I save my secret keys and password securely in my version control system?
- [Django]-Error: No module named psycopg2.extensions
- [Django]-Django 1.7 โ App 'your_app_name' does not have migrations
16๐
When it comes to date-pickers my choice is Bootstrap Datepicker. You can implement it in your django app by using django-bootstrap-datepicker-plus which works both on newer and older DJango versions. I maintain the repository and tested it working in DJango version 1.8, 1.10, 1.11 and 2.0.4.
The setup is quite easy. You just install it.
pip install django-bootstrap-datepicker-plus
Import the widget in your forms.py file
from bootstrap_datepicker_plus import DatePickerInput
Add the widget to your date field
class ToDoForm(forms.Form):
date = forms.DateField(
widget=DatePickerInput(
options={
"format": "mm/dd/yyyy",
"autoclose": True
}
)
)
Detailed instructions are available on the django-bootstrap-datepicker-plus Github Page.
Disclaimer: This widget package is now owned and maintained by me. For any issues with it feel free to open issues on the Github Page.
- [Django]-Django-DB-Migrations: cannot ALTER TABLE because it has pending trigger events
- [Django]-How to assign items inside a Model object with Django?
- [Django]-Django+Postgres: "current transaction is aborted, commands ignored until end of transaction block"
14๐
aviโs solution can also be done without using an additional django input class:
class PromiseForm(ModelForm):
class Meta:
model = Promise
fields = ['title', 'description', 'made_on']
widgets = {
'made_on': DateInput(attrs={'type': 'date'}),
}
- [Django]-Where are the Assertion Methods list from Django TestCase?
- [Django]-Django aggregate or annotate
- [Django]-Pass extra arguments to Serializer Class in Django Rest Framework
6๐
Being newer to coding, I used this example due to itโs ease.
<form method="POST">{% csrf_token %}
<p>Start date<input type = 'date' name='start_date' ></p>
<p>End date<input type = 'date' name='end_date' ></p>
<button type="submit">Submit</button>
</form>
- [Django]-How can I unit test django messages?
- [Django]-Simple Log to File example for django 1.3+
- [Django]-How to get the currently logged in user's id in Django?
3๐
Hereโs an ultra simple way using just html5 and django:
forms.py
class DateInput(forms.DateInput):
input_type = 'date'
class DateForm(forms.Form):
start_date = forms.DateField(widget=DateInput)
end_date = forms.DateField(widget=DateInput)
Views.py
def search_dates(request, pk=''):
if request.method == "GET": # select dates in calendar
form = DateForm()
return render(request, 'search.html', {"form":form})
if request.method == "POST": # create cart from selected dates
form = DateForm(request.POST)
if form.is_valid():
start = form.cleaned_data['start_date']
end = form.cleaned_data['end_date']
start_date = datetime.strftime(start, "%Y-%m-%d")
end_date = datetime.strftime(end, "%Y-%m-%d")
print(start_date)
print(end_date)
return render(request, 'search.html', {"form":form})
Template
<form method="post">
{% csrf_token %}
{{ form.as_table }}
<p style="text-align: center"><input type="submit" value="Search"></p>
</form>
- [Django]-How to add superuser in Django from fixture
- [Django]-Unique fields that allow nulls in Django
- [Django]-Phpmyadmin logs out after 1440 secs
2๐
I found this quite smooth for a DateTimeField
friendly option https://github.com/asaglimbeni/django-datetime-widget
Needed to include bootstrap-timepicker css file from malot and it worked quite neatly.
- [Django]-Retrieving a Foreign Key value with django-rest-framework serializers
- [Django]-Django query get last n records
- [Django]-How do I do a not equal in Django queryset filtering?
2๐
This is what worked for me . I am using Django 1.11 with bootstrap 3.3 .
Form.py
from django.contrib.admin.widgets import AdminDateWidget
class AddInterview(forms.ModelForm):
class Meta:
model = models.Interview
fields = ['candidate', 'date', 'position', 'question_set']
date = forms.DateField(widget=AdminDateWidget())
Template:
<form method="post">
<div class="form-group">
{% csrf_token %}
{{ form.media }}
{{ form.as_p }}
<p>Note: Date format is yyyy-mm-dd</p>
</div>
CSS: (In same above html template file)
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/forms.css' %}"/>
<link rel="stylesheet" type="text/css" href="{% static 'admin/css/widgets.css' %}"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" >
JS:(In same above html template file)
<script type="text/javascript" src="/admin/jsi18n/"></script>
<script type="text/javascript" src="{% static 'admin/js/core.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/admin/RelatedObjectLookups.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/vendor/jquery/jquery.min.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/jquery.init.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/actions.min.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/calendar.js' %}"></script>
<script type="text/javascript" src="{% static 'admin/js/admin/DateTimeShortcuts.js' %}"></script>
- [Django]-Django database query: How to get object by id?
- [Django]-Django: Adding "NULLS LAST" to query
- [Django]-How to add a cancel button to DeleteView in django
2๐
Here is my favorite implementation that works directly from CreateView
.
from django.views.generic import CreateView
from django.contrib.admin.widgets import AdminDateWidget
from .models import MyModel
class MyModelCreateView(CreateView):
template_name = 'form.html'
model = MyModel
fields = ['date_field', ...]
def get_form(self, form_class=None):
form = super(MyModelCreateView, self).get_form(form_class)
form.fields['date_field'].widget = AdminDateWidget(attrs={'type': 'date'})
return form
The only thing that could be easier is to have this be the default behavior for Generic CBVs!
- [Django]-Readonly models in Django admin interface?
- [Django]-Django in / not in query
- [Django]-Django โ limiting query results
1๐
This is what i do to get datepicker in django forms.
install bootstrap_datepicker_plus by pip command.
pip install django-bootstrap_datepicker_plus
forms.py
from .models import Hello
from django import forms
from bootstrap_datepicker_plus import DatePickerInput
class CreateForm(forms.ModelForm):
class Meta:
model = Hello
fields =[
"Date",
]
widgets = {
'Date': DatePickerInput(),
}
settings.py
INSTALLED_APPS = [
'bootstrap_datepicker_plus',
]
- [Django]-ValueError: The field admin.LogEntry.user was declared with a lazy reference
- [Django]-Django Generic Views using decorator login_required
- [Django]-Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4
0๐
I have been struggling with a similar problem and I found the following solution pleasing, using floppy forms:
This works really well and is relatively easy to implement, hope someone will find it help full. Good luck.
- [Django]-Tailwindcss: fixed/sticky footer on the bottom
- [Django]-Django reverse lookup of foreign keys
- [Django]-Django check for any exists for a query
0๐
Use datetime-local
as type for the input.Its not very fancy looking.But will do the Job
- [Django]-Django: Get an object form the DB, or 'None' if nothing matches
- [Django]-Django โ How to set default value for DecimalField in django 1.3?
- [Django]-Django-allauth: Linking multiple social accounts to a single user
0๐
Just adding this line of code to my template html, solved my problem:
<div class="mb-3">
<label for="exampleFormControlInput1" class="form-label">Email address</label>
<input type="date" class="form-control" id="exampleFormControlInput1" placeholder="name@example.com">
</div>
- [Django]-PicklingError: Can't pickle <class 'decimal.Decimal'>: it's not the same object as decimal.Decimal
- [Django]-Django rest framework lookup_field through OneToOneField
- [Django]-Automated django receive hook on server: respond to collectstatic with "yes"