Django Custom Calendar Widget

I am trying to add calendar input to one of my forms. There is a wonderful calendar widget that Django uses on its admin pages, but I cannot figure out how to add it to a custom form.

I found a couple of other questions on the same issue here, but they all seemed outdated, complicated and didn't work.

Is there a way to incorporate Django, a built-in calendar widget, into one of my forms?

+15
source share
5 answers

I realized this thanks to Dave S. and a number of old posts on this subject. My successful method:

Create a custom form.

from django.contrib.admin.widgets import AdminDateWidget. , my_field = DateField(widget = AdminDateWidget), .

, css/js:

{% load i18n admin_modify adminmedia %}
{% block extrahead %}{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% admin_media_prefix %}css/base.css" />
<link rel="stylesheet" type="text/css" href="{% admin_media_prefix %}css/widgets.css" />
<script type="text/javascript" src="/jsi18n/"></script>
<script type="text/javascript" src="{% admin_media_prefix %}js/core.js"></script>
{{ form.media }}
{% endblock %}

. , Django , . , , .

, , JS . !

+10

, django-admin, django/contrib/admin/widgets.py. . , AdminDateWidget.

from django.contrib.admin.widgets import AdminDateWidget
from django.forms.fields import DateField

class MyForm(Form):
    my_field = DateField(widget=AdminDateWidget)

. , , AdminDateWidget.

+7

/ Django .

@Dave S @MrGlass, Django 1.2 , JavaScript -:

{% load adminmedia %} /* At the top of the template. */

/* In the head section of the template. */
<script type="text/javascript">
window.__admin_media_prefix__ = "{% filter escapejs %}{% admin_media_prefix %}{% endfilter %}";
</script>

(from Karl Meyer answer )

0
source

You can do this with the widget of the form "SelectDateWidget ()", as in this example:

class MyForm(forms.Form):

        start_date=forms.DateField(widget = forms.SelectDateWidget())
        end_date=forms.DateField(widget = forms.SelectDateWidget())
0
source

Source: https://habr.com/ru/post/1626916/


All Articles