📜 ⬆️ ⬇️

How easy it is to make a calendar and a clock for entering the date and time on a form

or rather, to use those already available in Django (the ones that the default is in the administration interface) ...



I started, naturally, with the study of how it was done in the admin panel. Everything turned out to be quite simple, but with a couple of instructive examples.
')
First, I found where this beautiful calendar lies and how it is stuck to the input field: DateTimeShortcuts.js, there is an instruction in it:
 // Inserts shortcut buttons after all of the following:
 // <input type = "text" class = "vDateField">
 // <input type = "text" class = "vTimeField">

Only then it turned out that this file does not work without the others, namely without i18n.js, core.js and calendar.js - they also need to be included in the template that will be used to display the form. I also had several files with styles, in my opinion, there were also a few, but I took only what was necessary and copied it into my calendar.css, so that I could easily modify it — everything is set up with a bang. The scripts, by the way, I also dragged into my folder, because on the one hand it’s somehow not serious when something is included with the / admin / path, and on the other hand, “it will suddenly have to be corrected” (needed).

The next step was to understand how widget is implemented for separate input of date and time (I honestly did not know that, from the point of view of the form class, this is one field with a tricky widget and I planned to simply make 2 TextInput input fields and register classes for them). The approach is very elegant:
 class EventSplitDateTime (forms.SplitDateTimeWidget):
     def __init __ (self, attrs = None):
         widgets = [forms.TextInput (attrs = {'class': 'vDateField'}), 
                    forms.TextInput (attrs = {'class': 'vTimeField'})]
         # Note that we're calling MultiWidget, not SplitDateTimeWidget, because
         # we want to define widgets.
         forms.MultiWidget .__ init __ (self, widgets, attrs)

     def format_output (self, rendered_widgets):
         return mark_safe (u '% s <br />% s'% (rendered_widgets [0], rendered_widgets [1]))

and, accordingly, the use becomes elementary:
 class EventForm (forms.Form):
     start = forms.DateTimeField (label = ugettext ("Start"), widget = EventSplitDateTime ())
     end = forms.DateTimeField (label = ugettext ("End"), widget = EventSplitDateTime ())


That's all :-) especially strictly do not judge. How the result looks like can be found here .

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


All Articles