Code Monkey home page Code Monkey logo

django-tempus-dominus's Introduction

Django Tempus Dominus

Django Tempus Dominus provides Django widgets for the Tempus Dominus v6 date and time picker.

Installation

  • From PyPI: pip install django-tempus-dominus

Then add tempus_dominus to INSTALLED_APPS in your Django settings.

Usage & Django Settings

The following settings are available:

  • TEMPUS_DOMINUS_LOCALIZE (default: False): if True, widgets will be translated to the selected browser language and use the localized date and time formats.
  • TEMPUS_DOMINUS_INCLUDE_ASSETS (default: True): if True, loads Tempus Dominus and moment JS and CSS from Cloudflare's CDN, otherwise loading the JS and CSS is up to you.
  • TEMPUS_DOMINUS_DATE_FORMAT (default: yyyy-MM-dd)
  • TEMPUS_DOMINUS_DATETIME_FORMAT (default: yyyy-MM-dd HH:mm:ss)
  • TEMPUS_DOMINUS_TIME_FORMAT (default: HH:mm:ss)
  • TEMPUS_DOMINUS_CSS_CLASS (default: form-control): this CSS class will be applied to the form input, defaulting to Bootstrap's form-control. It can be overridden by passing attrs during instantiation.
  • TEMPUS_DOMINUS_ICON_PACK (default: fa_five): the icon pack to use. Accepted values:
    • fa_five: FontAwesome 5
    • bi_one: Bootstrap Icons 1

Three widgets are provided:

  • DatePicker
    • Defaults to L if TEMPUS_DOMINUS_LOCALIZE is True, otherwise TEMPUS_DOMINUS_DATE_FORMAT
  • DateTimePicker
    • Defaults to L LTS if TEMPUS_DOMINUS_LOCALIZE is True, otherwise TEMPUS_DOMINUS_DATETIME_FORMAT
  • TimePicker
    • Defaults to LTS if TEMPUS_DOMINUS_LOCALIZE is True, otherwise TEMPUS_DOMINUS_TIME_FORMAT

In your Django form, you can use the widgets like this:

from django import forms
from tempus_dominus.widgets import DatePicker, TimePicker, DateTimePicker

class MyForm(forms.Form):
    date_field = forms.DateField(widget=DatePicker())
    date_field_required_with_min_max_date = forms.DateField(
        required=True,
        widget=DatePicker(
            options={
                'restrictions': {
                    'minDate': '2009-01-20',
                    'maxDate': '2017-01-20',
                }
            },
        ),
        initial='2013-01-01',
    )
    """
    In this example, the date portion of `defaultDate` is irrelevant;
    only the time portion is used. The reason for this is that it has
    to be passed in a valid MomentJS format. This will default the time
    to be 14:56:00 (or 2:56pm).
    """
    time_field = forms.TimeField(
        widget=TimePicker(
            options={
                'defaultDate': '1970-01-01T14:56:00',
                'restrictions': {
                    'enabledHours': [9, 10, 11, 12, 13, 14, 15, 16]
                }
            },
        ),
    )
    datetime_field = forms.DateTimeField(
        widget=DateTimePicker(
            options={
                'useCurrent': True,
            },
        ),
    )

Then in your template, include jQuery, {{ form.media }}, and render the form:

<html>
  <head>
    {# Django Tempus Dominus assets are included in `{{ form.media }}` #}
    {{ form.media }}
  </head>
  
  <body>
    <div class="container">
      <div class="row">
        <div class="col">
          <form method="post" action=".">
            {% csrf_token %}
            {{ form.as_p }}
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

Widget Options

  • options (dictionary): This dictionary will be passed to Tempus Dominus. A full list of options is available here.
  • input_toggle (boolean, default True): Controls whether clicking on the input field toggles the datepicker popup. Typically is set to False when an icon is in use.
  • input_group (boolean, default True): Whether to include a Bootstrap 4 input-group around the picker.
  • size (string): Controls the size of the input group (small or large). Defaults to the default size.
  • prepend (string): Name of a Font Awesome icon to prepend to the input field (fa fa-calendar).
  • append (string): Name of a Font Awesome icon to append to the input field (fa fa-calendar).
  • icon_toggle (boolean, default True): Controls whether clicking on the icon toggles the datepicker popup. Typically is set to False when an icon is in use.

Release Notes and Contributors

Maintainers

This package is largely maintained by the staff of Wharton Research Data Services. We are thrilled that The Wharton School allows us a certain amount of time to contribute to open-source projects. We add features as they are necessary for our projects, and try to keep up with Issues and Pull Requests as best we can. Due to time constraints (our full time jobs!), Feature Requests without a Pull Request may not be implemented, but we are always open to new ideas and grateful for contributions and our package users.

django-tempus-dominus's People

Contributors

adamchainz avatar axtheb avatar bcollazo avatar cdchen avatar dcstlouis avatar deyspring avatar flipperpa avatar ianastewart avatar johnnyporkchops avatar kennethlove avatar kevswanberg avatar manuelkappler avatar nick-traeger avatar pax0r avatar rgs258 avatar theunraveler avatar violuke avatar waymao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-tempus-dominus's Issues

To do before v6 release

  • Review icon settings. No more font awesome.
  • Check toggle settings
  • Review options being passed to underlying JS library
  • Test suite is passing, but build a testable app as part of the test suite with manage.py

Allow setting custom tempus-dominus format globally

Currently, there are only two options to select date format from: "L" or "YYYY-MM-DD" (with TEMPUS_DOMINUS_LOCALIZE True or False).
Sometimes it is desirable to use a format other than the two above (like, for example, DD/MM/YYYY or YYYY.MM.DD). In such case, the only way is to pass it in options to every widget instance which causes a lot of duplication.
It would be nice to have the ability to set a custom date format once for all widgets via settings.

date argument to javascript should always be passed in non-localized format.

when I display form translated to czech language, it tries to display date in local datetime format (DD.MM.YYYY HH:mm:ss), but javascript does not parse it to any date, so the datetime field immediatelly blanks. Console shows warning (value provided is not in a recognized RFC2822 or ISO format).

When I manually reformat the date argument to datetimepicker js to YYYY-MM-DD HH:mm:ss format it starts to work.

tempus not triggering when using cripsy forms helper

When I render the form in my template using {{ form|crispy }} everything works.

But when I try to apply some layouts using crispy form helper and render the form using {% crispy form %}, tempus doesn't get triggered

Django datetimepicker does not have time option

Great plugin, but I cannot get the timepicker, only the datepicker. Would be great if you could help.

base.generic.html

<!DOCTYPE html>
<html lang="en">

<head>
  {% block title %}<title>Local Library</title>{% endblock %}
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <!-- Include FontAwesome; required for icon display -->
  <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.css">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
    integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
  <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <!-- Add additional CSS in static file -->
  {{ form.media }}
</head>

<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-sm-10 ">
        {% block content %}{% endblock %}
        {% block pagination %}{% endblock %}
        {% block footer %}{% endblock %}
      </div>
    </div>
  </div>
</body>

</html>

auction_form.html inherits -

{% extends "base_generic.html" %}

{% block content %}
  <form action="" method="post">
    {% csrf_token %}
    <table>
    {{ form.as_table }}
    </table>
    <input type="submit" value="Submit">
  </form>
{% endblock %}

forms.py:

from django import forms
from django.core.exceptions import ValidationError
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
import datetime
from tempus_dominus.widgets import DatePicker, TimePicker, DateTimePicker

from .models import Auction

class AuctionCreateForm(forms.ModelForm):
    def clean_start(self):
        inputted_start = self.cleaned_data['start']
        if inputted_start < timezone.now():
            raise ValidationError(_('Invalid date - start in past'))
        # might want to restrict when it can start in the future
        # e.g must start today

        return inputted_start

    def clean_end(self):
        inputted_start = self.cleaned_data['start']
        inputted_end = self.cleaned_data['end']
        if inputted_end <= inputted_start:
            raise ValidationError(_('Invalid date - end not after the start'))
        if inputted_end > inputted_start + datetime.timedelta(minutes=5):
            raise ValidationError(_('Invalid date - auction longer than 5 minutes'))
        
        return inputted_end

    class Meta:
        model = Auction
        fields = ['title', 'start', 'end', 'reserve']
        labels = {'reserve': _('Reserve')}
        help_texts = {'end': _('Enter a date between now and the next seven days')}

    start = forms.DateTimeField(
        widget=DatePicker(
            options={
                'minDate': (
                    datetime.date.today() + datetime.timedelta(days=1)
                ).strftime(
                    '%Y-%m-%d'
                ),  # Tomorrow
                'useCurrent': True,
                'collapse': False,
            },
            attrs={
                'append': 'fa fa-calendar',
                'icon_toggle': True,
            }),
    )
    end = forms.DateTimeField(
        widget=DatePicker(
            options={
                'minDate': (
                    datetime.date.today() + datetime.timedelta(days=1)
                ).strftime(
                    '%Y-%m-%d'
                ),  # Tomorrow
                'useCurrent': True,
                'collapse': False,
            },
            attrs={
                'append': 'fa fa-calendar',
                'icon_toggle': True,
            }),
    )

Views.py

class AuctionCreate(LoginRequiredMixin, CreateView):
    """ View function for creating an auction """
    form_class = AuctionCreateForm
    template_name = "auction/auction_form.html"

    def form_valid(self, form):
        form.instance.creator = self.request.user
        return super().form_valid(form)

initial value for the widget

Hi,
I've set an initial value to a TimePicker, it seems not to be rendered in the piker on the page: the moment_option method tries to format a date, not a time...

Thanks !

Options not reflected

Hello team!

I am working on a website for a restaurant and want to implement Tempus Dominus on the reservation page.

It is displaying and working as intended, but I can not for the life of me get the options to reflect on the page.

This is the form.py code in question:

datetime_field = forms.DateTimeField(
	label="日にち",
	widget=DateTimePicker(
		options={
			'enabledHours': [17, 18, 19, 20, 21, 22],
			'minDate': date.today().strftime("%Y-%m-%d"),
			'format': 'YYYY/MM/D HH:mm',
			'locale': 'ja',
			'useCurrent': True,
			'collapse': False,
		},
		attrs={
			'append': 'fa fa-calendar',
			'icon_toggle': True,
		}
	),
)

For the locale, I have included Moment.js in the header of the base template, as noted below.

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/locale/ja.js" integrity="sha256-CFWtR1hGN/5Vc+kcJkqeMFND0g6gFFZdnSqUtdL7WOQ=" crossorigin="anonymous"></script>

When I run python manage.py runserver, this is the result I am getting.

Dominus1

Dominus2

As you can see, the options I put in forms.py are not being reflected. Also, the styling seems to be slightly off, but I don't want to clog up this issue.

Can anybody tell me where I am going wrong? If you need any additional information, please let me know.

Thank you very much in advance!

Jquery call & initialization order

I have jquery loaded just before </body>. This conflicts with jquery call which is caused by field in the middle of the page.
Is there a way of handling that? Perhaps it's Django issue?

Widget does not work properly with formsets (existing values are not displayed)

A javascript function containing the picker_id in its name is dynamically generated for each widget (widget.html, line 19).

In a formset, Django dynamically generates identifiers for each form in a formset in the format 'id_table-number-Field'. Thus, the picker_id contains a hyphen which must not be part of a function name in JavaScript. This causes an error when the page is loaded. The picker does not display an existing field value.

A simple solution would be to replace any hyphen in the picker_id by an underscore.

Duplicate id on div.input-group child input

Hi,

the Django Widget generates the following incorrect HTML Code:

<div class="input-group " id="id_myinput" data-target-input="nearest">
    <input type="text" name="myinput" class="form-control datetimepicker-input" required="True" id="id_myinput" data-toggle="datetimepicker" data-target="#id_myinput">
</div>

The Element #id_myinput appears twice in DOM, breaking e.g. labels focus functionality.

Version 5.1.2.1

Documentation regarding template should be improved.

The template that is shown does not work if simply copied verbatim.
Firstly, you should mention that bootstrap.css should be loaded, though that should be obvious.
Secondlt, please mention that font awesome is needed for the icons on the date picker to appear correctly. I found that it does not show the clock icon correctly on the date and time picker when you use the latest version 5 of font awesome from the cdn. It's best to stick to version 4.7, which is what is used in the tempus dominus demo pages. Maybe that fiel should be part of form.media.
And finally, unless you put the form inside a container, and a column (or more likely a container, row and column), tempus-dominus will pause on an exception: "datetimepicker component should be placed within a relative positioned container".
I have incorporated all of the above in the attached file.

template.txt

Hour and Minutes TimePicker

Hello,

Is there a way that I can show Hour and Minute?

Below is the code I'm currently using.

`class ClientForm(forms.ModelForm):

class Meta:
    model = Client
    fields = ('fullname', 'email', 'phone', 'date', 'time', 'service')
    widgets = {
        'date': DatePicker(
            options={
                'minDate': (datetime.datetime.today() + datetime.timedelta(days=1)).strftime('%Y-%m-%d 00:00:00'),
                # 'maxDate': (datetime.datetime.today() + datetime.timedelta(days=2)).strftime('%Y-%m-%d 23:59:59')
            }
        ),
        'time': TimePicker(
            options={
                'enabledHours': [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
            }
        )
    }`

Thanks in advance and more power.

Invalid syntax

Hey,

I've just added this to my Django project with basic setup and it's giving me a syntax error:

File "../forms.py", line 12, in <module>
    from tempus_dominus.widgets import DateTimePicker
  File "../python2.7/site-packages/tempus_dominus/widgets.py", line 46
    self.js_options = {**self.js_options, **options}
                      ^
SyntaxError: invalid syntax

Any Ideas? Guessing its only Python 3+?

Use a django template instead of a python str template

H',
It would be more "django-ic" to use a plain django template as widget template, and more expandable / customable.

I'm using webpack as js loader, I've to customize the template, and I'm stuck with the python template.

The render would greatly benefit of it, building a context to pass to a django template

Thanks !

Replace dashes with underscores in id breaks prefixed formsets

Hi there,

I just noticed this fix edc223b#diff-8e24002ea598cd18c3aae0208259ebeb from September. Adding this line all_attrs["id"] = all_attrs["id"].replace('-', '_') (widgets.py?#L80)

I've been trying to hunt down some issues with inline formsets that cropped up and tracked it down to this bug. Why was this change made and can it be reversed?

(Dynamic) Inline formsets rely on replacing a fixed prefix with the form number (generally looking for -__prefix__- so replacing the dashes breaks things.

Just to note, version 5.1.2.5 worked without any trouble.

On another note, I noticed that whenever an installation of django-tempus-dominus is forced with pip it also seems to reinstall all dependencies (like Django). This doesn't seem to happen with other packages.

Initial value not displaying with TimePicker widget

Hi again,

I have had some difficulties using the TimePicker for update views (UpdateView), as I can't get it to display the initial value of the object to be updated, see the pictures below. As the pictures show, I have had no issues with DateTimePicker and its initial value (no issues with the DatePicker either).

Picture with TimePicker:

image

Picture without TimePicker:

image

My widget looks as follows:

class TaskUpdateForm(forms.ModelForm):
    class Meta:
        ...
        widgets = {
            "start_time": TimePicker(
                options={"format": "HH:mm:ss"},
                attrs={
                    "append": "far fa-clock",
                    "input_toggle": False,
                    "icon_toggle": True,
                },
            ),
        }

Can you tell, based on this information, whether this issue is on my or your end, and if so suggest what can be done to solve it?

I hope you can help.

Best regards,
Niels

Clock icon not showing Fontawesome 5

Thank you for the development of this widget. The clock icon is not showing even redefining the constructor this way:

$.fn.datetimepicker.Constructor.Default = $.extend({}, $.fn.datetimepicker.Constructor.Default, {
        icons: {
            time: "far fa-clock",
            date: "fa fa-calendar",
            up: "fa fa-arrow-up",
            down: "fa fa-arrow-down",
            previous: "fa fa-chevron-left",
            next: "fa fa-chevron-right",
            today: "fa fa-calendar-check-o",
            clear: "fa fa-delete",
            close: "fa fa-times"
        }
    });

The problem is that the clock icon is initialized in the init of the widgets.py file:

def __init__(self, attrs=None, options=None):
    super().__init__()
    self.js_options = {
        "format": self.get_js_format(),
        "icons": {"time": "fa fa-clock-o"},
    }

and thus, the only way of changing the icon is to instantiate the widget like this:

date = forms.DateTimeField(widget=DateTimePicker(options={'useCurrent': True}, attrs={
    'append': 'fa fa-calendar',
    'autocomplete': 'off'}), label="Date")

#Fix clock icon Fontawesome 5
date.widget.js_options["icons"] = {"time": "far fa-clock"}

Could modified so that the icon is not hard-coded?

Best regards,
Manuel.

Additional parameters not supported by widget

Hi,
I'm trying to pass the appendparameter to the widget, and have an issue:

from tempus_dominus.widgets import DateTimePicker

class FooForm(forms.ModelForm):
    class Meta:
        model = Foo
        fields = ("start_at",)
        widgets = {"start_at": DateTimePicker(options={"useCurrent": False}, append="fa fa-calendar")}

I've an the following issue:

TypeError: __init__() got an unexpected keyword argument 'append'

Thanks for your help !

Make containing <div class="input-group"> optional

The current widget template is thus:

<div class="input-group{% if size == 'small' %} input-group-sm{% elif size == 'large' %} input-group-lg{% endif %}"
  id="div_{{ picker_id }}" data-target-input="nearest">
  {% if prepend %}
    <div class="input-group-prepend" data-target="#{{ picker_id }}" {% if icon_toggle %}data-toggle="datetimepicker"{% endif %}>
      <div class="input-group-text"><i class="{{ prepend }}"></i></div>
    </div>
  {% endif %}
  <input type="{{ type }}" name="{{ name }}"{{ attrs }} {% if input_toggle %}data-toggle="datetimepicker"{% endif %}
         data-target="#{{ picker_id }}">
  {% if append %}
    <div class="input-group-append" data-target="#{{ picker_id }}" {% if icon_toggle %}data-toggle="datetimepicker"{% endif %}>
        <div class="input-group-text"><i class="{{ append }}"></i></div>
    </div>
  {% endif %}
</div>
<script type="text/javascript">
    $(function () {
        $('#{{ picker_id }}').datetimepicker({{ js_options }});
    });
</script>

On line 1 you can see there is no {% if x %} on the upper most container div. By default I think this is what most people want but there is no way with an options parameter for example, to disable the usage of this div. This is a problem if someone wanted to, for example, display multiple datepickers inline sort of like this example shown in the bootstrap docs.

Recursion bug when refreshing a page with data already entered

Create a Django form with a date field using the datepicker (format option = DD/MM/YYYY though this is not material) and a time field using the timepicker. Load the page. Both widgets work correctly.
image
But if you then refresh the page without first saving it, the date field is preloaded with the previously selected date and also displays a time of 12am.
image
Similarly the time field displayes a full data and time. An attempt to change the date results in a jQuery error: too much recursion. See trace from Firefox below:

jQuery.Deferred exception: too much recursion
xe@http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:7138
Fe@http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:8658
@http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:7668
I/E[t[0]]@http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:4760
A/V[t]</<@http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:5165
A@http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:5199
ln.format@http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:30586
f</u</i.prototype._setValue@http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:8126
f</u</i.prototype._int@http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:6984
i@http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:6495
k@http://cdn…
undefined jquery-3.3.1.min.js:2:30920
[Show/hide message details.] too much recursion[Learn More] moment.min.js:1:7138
xe
http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:7138
Fe
http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:8658

http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:7668
I/E[t[0]]
http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:4760
A/V[t]</<
http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:5165
A
http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:5199
ln.format
http://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.0/moment.min.js:1:30586
f</u</i.prototype._setValue
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:8126
f</u</i.prototype._int
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:6984
i
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:6495
k
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:29086
l</k._jQueryHandleThis
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:7:22196
l</k._jQueryInterface
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:7:22406

http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:7:22730
dispatch
https://code.jquery.com/jquery-3.3.1.min.js:2:41720
add/y.handle
https://code.jquery.com/jquery-3.3.1.min.js:2:39774
trigger
https://code.jquery.com/jquery-3.3.1.min.js:2:69549
trigger/<
https://code.jquery.com/jquery-3.3.1.min.js:2:70138
each
https://code.jquery.com/jquery-3.3.1.min.js:2:2571
each
https://code.jquery.com/jquery-3.3.1.min.js:2:1238
trigger
https://code.jquery.com/jquery-3.3.1.min.js:2:70117
f</u</i.prototype._notifyEvent
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:10392
f</u</i.prototype._setValue
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:8542
f</u</i.prototype._int
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:6984
i
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:6495
k
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:29086
l</k._jQueryHandleThis
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:7:22196
l</k._jQueryInterface
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:7:22406

http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:7:22730
dispatch
https://code.jquery.com/jquery-3.3.1.min.js:2:41720
add/y.handle
https://code.jquery.com/jquery-3.3.1.min.js:2:39774
trigger
https://code.jquery.com/jquery-3.3.1.min.js:2:69549
trigger/<
https://code.jquery.com/jquery-3.3.1.min.js:2:70138
each
https://code.jquery.com/jquery-3.3.1.min.js:2:2571
each
https://code.jquery.com/jquery-3.3.1.min.js:2:1238
trigger
https://code.jquery.com/jquery-3.3.1.min.js:2:70117
f</u</i.prototype._notifyEvent
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:10392
f</u</i.prototype._setValue
http://cdnjs.cloudflare.com/ajax/libs/tempusdominus-bootstrap-4/5.0.0-alpha14/js/tempusdominus-bootstrap-4.min.js:6:8542

Passing datetime as option only initialized on server restart

In the following example, won't the minDate only be initialized when the server starts?

(datetime.date.today() + datetime.timedelta(days=1)).strftime('%Y-%m-%d')

So if I run this today 2019-01-24 it will result in 2019-01-25. But then tomorrow (unless server has been restarted) it will still be the same value?

datetime_field = forms.DateTimeField(
        widget=DateTimePicker(
            options={
                'minDate': (datetime.date.today() + datetime.timedelta(days=1)).strftime('%Y-%m-%d'),  # Tomorrow
                'useCurrent': True,
                'collapse': False,
            },
            attrs={
               'append': 'fa fa-calendar',
               'input_toggle': False,
               'icon_toggle': True,
            }
        ),
    )

DateTime pickup not displaying on template extending

Hi and thanks for this awesome work !

I'm trying to get your library working on my project but I'm facing a bug :
I got a "base.html" template which is a simple html snippet loading all the requirements in the head : bootstrap & jquery following your documentation.

I also created a simple block called "media" which is just after the calls to jquery and bootstrap's CDNs.

Calling {{form.media}} inside the media block from my "form.html" template which extends base.html populates the DOM fine, but the datetimepicker dont show up. Moving {{form.media}} inside the

doesn't work neither. But, just outside the "content" block, it works.

Another thing : I'm french, and using my locale the field wont validate. I have to remove my config to make it work.

Thanks for looking at it :)

Widget attributes are ignored

If attributes such as disabled or required=False are specified for a widget they get ignored in the mixin. See pull request to fix.

No icons are rendered

Thank you for this widget.

Unfortunately, no icons are displaying either in Chrome or Explorer, I followed installation instructions and I am using Django 2.2.

The output I see is:

image

My script is below. Thank you.
Gerhard

My HTML file is:

<!DOCTYPE html>
<html lang="en">

  <head>
      {% block title %}<title>Tempus Dominus</title>{% endblock %}
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">

      {# Include FontAwesome; required for icon display #}
      <link rel="stylesheet" href="https://netdna.bootstrapcdn.com/font-awesome/4.7.0/css/font- 
                                awesome.css">

      {# Include Bootstrap 4 and jQuery #}
      <link rel="stylesheet"href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
      <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>

      {# Django Tempus Dominus assets are included in `{{ form.media }}` #}
      {{form.media }}

  </head>
 
  <body>
    <div class="container">
      <div class="row">
        <div class="col">
          <form method="get" action="{% url 'date_picker_page' %}">
            {{form.as_p }}
	    <button type="submit">Go</button>
          </form>
        </div>
      </div>
    </div>
  </body>
</html>

My form is

class DatePickerForm(forms.Form):
    the_date = forms.DateField(widget=DatePicker())

My view is

class DatePickerPage(View):
    form_class = DatePickerForm
    template_name = 'date_picker_page.html' 
	
    def get(self, request):
        if self.request.GET.get('the_date', default=None) is None:
	    the_date=None
	else:
	    # form filled in
	    form = self.form_class(data=request.GET)
	    form.is_valid()
	    the_date = form.cleaned_data.get('the_date')
			
	print(the_date)

        context={'form':self.form_class()}
	template = loader.get_template(self.template_name)
	output = template.render(context, request)
	return HttpResponse(output)``

Errors are hidden

Errors are hidden:

We have form:

class EventForm(forms.ModelForm):
    date_start = forms.DateTimeField(
        widget=DateTimePicker(
            options={
                'useCurrent': True,
                'collapse': True,
            },
            attrs={
                'append': 'fa fa-calendar',
                'icon_toggle': True,
            }
        ),
    )
    date_end = forms.DateTimeField(
        widget=DateTimePicker(
            options={
                'useCurrent': True,
                'collapse': True,
            },
            attrs={
                'append': 'fa fa-calendar',
                'icon_toggle': True,
            }
        ),
    )

    class Meta:
        model = Event
        fields = '__all__'

    def clean_date_end(self):
        if self.cleaned_data.get('date_end') < self.cleaned_data.get('date_start'):
            raise ValidationError('date_end < date_start!')
        return self.cleaned_data.get('date_end')

if date_end < date_start then raise ValidationError('date_end < date_start!'), but html output:

<p id="error_1_id_date_end" class="invalid-feedback"><strong>date_end < date_start!</strong></p>

and class="invalid-feedback" style attribute:

.invalid-feedback {
    display: none;
    width: 100%;
    margin-top: .25rem;
    font-size: 80%;
    color: #dc3545;
}

.invalid-feedback has display: none

'datetimepicker' is not a function

I'm not sure if what I'm seeing is a bug or a mistake on my part, but I'm getting the following error:

TypeError: $(...).datetimepicker is not a function

From the following generated html:

<div class="row">
	<form action="" method="post" class="graphConfig">		
		<ul>
			<input type="hidden" name="csrfmiddlewaretoken" value="aj2SpLuX4U3bzxNFfVarg6tKK0Y8qThhHkDrzYzHMSDWJUj83zHjVOE4Ngqv2fSq">
			<li><label for="id_your_name">Your name:</label> <input type="text" name="your_name" maxlength="100" required id="id_your_name"></li>
<li><label for="id_startDate">Startdate:</label> <div class="input-group"
  id="div_id_startDate" data-target-input="nearest">
  
  <input type="text" name="startDate" required="True" id="id_startDate" class="form-control  datetimepicker-input" data-toggle="datetimepicker"
         data-target="#id_startDate">
  
</div>
<script type="text/javascript">
    $(function () {
        $('#id_startDate').datetimepicker({"format": "%d.%m.%Y", "icons": {"time": "fa fa-clock"}, "minDate": "2019-02-02", "date": "2019-03-13"});
    });
</script>
</li>
			<input type="submit" value="Submit">
		</ul>
	</form>
</div>

I'm manually including jquery before the {{ form.media }} so all the scripts should be in the correct order, and using the embedded moment and bootstrap libs.

Everything seems to line up ok, but I'm not sure why the actual init function to pass in the params from the form is failing. Any ideas?

Thanks.

Django v2.7.1 final
Python 3.7.2
django-tempus-dominus 5.1.2.3
jquery 3.3.1

[Example] Rendering django-tempus-dominus in a MultiWidget

Hi all,
When you try to put django-tempus-dominus in a Django MultiWidget, it just renders a regular field. This is because the default renderer for MultiWidget expects the variable template_name to be present in the widget to describe how to render the widget.

Because django-tempus-dominus's template is full of variables, I think rendering this might be tricky (though it's probably possible with more knowledge than I have). As a workaround, I wrote this MultiWidget with a custom render method which invokes django-tempus-dominus' render method. It's a little hacky, but pretty effective.

The use case for this is if you want to use a SplitDateTimeField in your Form. Use this custom widget as the widget for the form, and in your model use a regular DateTimeField.

Hope this helps someone because it took me hours to figure out! If anyone has suggestions on a better way to do it, I'm all ears.

For this to work, there's a small tweak needed in django-tempus-dominus' widgets.py to support lists of values:

        if type(context["widget"]["value"]) is list:
            for value in context["widget"]["value"]:
                if value is not None:
                    options.update(self.moment_option(value))
        elif context["widget"]["value"] is not None:
            # Append an option to set the datepicker's value using a Javascript
            # moment object
            options.update(self.moment_option(value))

I'll submit this as a PR.

Here's the custom widget:
https://gist.github.com/nlittlejohns/748033df23a04f600801c8cfcc112c45

python to js serialization

Hi,

I've noticed an error on template rendering; The js_options data are not serialized into js object, and the boolean values appears as True, False and not true and false. I've done a work-around fixed it by adding:

const True = true; 
const False = false;

But it should be better to json-serialize the options on render.

Thanks again !

TimePicker is showing full date

For one of my forms, two fields are time fields, and so I have the following in forms.py.

`
class Meta:
model = DepotParameters
fields = 'all'

    widgets = {
        'window_start_time': TimePicker(
            options={
                'collapse': True,
                'keepInvalid': True
            }
        ),
        'window_end_time': TimePicker(
            options={
                'collapse': True,
                'keepInvalid': True,
            },
            attrs={'timepicker': True}
        )
    }

`.

However, when I'm rendering these fields in the HTML with {{ form.window_start_time}} and {{ form.window_end_time}}, the entire date is showing as the default value. Why isn't just the time displaying?

fa-clock to fa-clock-o

At line 42 on widgets.py change
'icons': {'time': 'fa fa-clock'}
with
'icons': {'time': 'fa fa-clock-o'}

Is there a way to change date/time-format

I've started using tempus dominus as a widget for my date, time and datetime widgets. I set TEMPUS_DOMINUS_LOCALIZE to True, which solved translation of the widget, however with the sideffect (which is also listed in the Readme) of picking up localized date and time formats. Is there an easy way to force a specific date or/and time format without losing the translation?

I tried to parse the format like the following, but it does not recognize the format:

widget=forms.DateInput(attrs={'class':'datepicker form-control', 'placeholder':'Select a date'}), format='%d/%m/%Y')

Also thanks for implementing this good looking date/timepicker widget into django.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.