Django calendar widget in a custom form

后端 未结 5 964
说谎
说谎 2021-01-31 04:25

I am trying to add a calendar date input to one of my forms. There is a wonderful calendar widget that Django uses on its admin pages, but I can\'t figure out how to add it to a

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-31 05:00

    I figured it out, thanks to Dave S. and a number of old posts on this topic. My successful method:

    Create a custom form.

    At the top, import the admin widgets using from django.contrib.admin.widgets import AdminDateWidget. Then, add the different fields of your form, using my_field = DateField(widget = AdminDateWidget) whenever you want to use the date widget.

    Create your form template

    Place the following toward the top to include the appropriate css/js files:

    {% load i18n admin_modify adminmedia %}
    {% block extrahead %}{{ block.super }}
    
    
    
    
    {{ form.media }}
    {% endblock %}
    

    Note: You do not necessarily need all of this, depending upon your version of Django and how you are implementing the form fields. this is what I found that I needed to use the widgets.

    Now just output your form like normal, and the JS should automatically convert it to a date field. Enjoy!

提交回复
热议问题