10

I'm new to Django and I'm trying to find the Django Admin date picker widget. I have search but got no results. Could anyone help me to use it on the project I'm working on?

I have a datetimefield in my model, like this:

fin = models.DateTimeField()

When creating a model from the admin is shows the widget but when I do it from the project it doesn't.

Rodrigo Munoz
  • 113
  • 1
  • 1
  • 4

3 Answers3

22

Specify the widget in your form as follows:

from django.contrib.admin.widgets import AdminDateWidget

class YourForm(forms.ModelForm):
        from_date = forms.DateField(widget=AdminDateWidget())

Don't forget to include the scripts and css in your template:

{{ form.media }}
Alex Morozov
  • 5,823
  • 24
  • 28
  • Hi Alex. Thank you for the reply. I'm still having problems to show the calendar and the "Now" feature. Is that external to the AdminDateWidget()? Is there a way I can see documentation about this? – Rodrigo Munoz Jan 15 '16 at 20:57
  • The common pitfall is to forget to include forms' media (css and js files) in the template. Have you done it? Like, `{{ form.media }}`. – Alex Morozov Jan 15 '16 at 21:20
  • 6
    @AlexMorozov Using only `{{ form.media }}` does not work. Other admin related css and js files have to be included as mentioned here http://stackoverflow.com/a/12916263/3590449 – Ibrahim Nov 29 '16 at 09:09
9

If for some reason you are looking to use the date picker with a PostgreSQL DateRangeField, you can do so like so:

from django.contrib.admin.widgets import AdminDateWidget
from django.contrib.postgres.forms.ranges import DateRangeField, 
RangeWidget

class YourForm(forms.ModelForm):
    date_range = DateRangeField(widget=RangeWidget(AdminDateWidget()))
Ben
  • 885
  • 1
  • 12
  • 25
0

This works for me inside Django-admin

class CustomAdminDateWidget(forms.DateInput):
    class Media:
        js = ("/admin/jsi18n/", 
              "/static/admin/js/vendor/jquery/jquery.js", 
              "/static/admin/js/calendar.js", 
              "/static/admin/js/jquery.init.js", 
              "/static/admin/js/admin/DateTimeShortcuts.js", 
              "/static/admin/js/core.js")

    def __init__(self, attrs=None, format=None):
        attrs = {'class': 'vDateField', 'size': '10', **(attrs or {})}
        super().__init__(attrs=attrs, format=format)

class DateRangeForm(forms.Form):
    start_date = forms.DateField(label='From Date', widget=CustomAdminDateWidget)
    end_date = forms.DateField(label='To Date', widget=CustomAdminDateWidget)

In the template head section

{{ form.media }}