twitter-bootstrap 如何在 Django 应用程序中使用 bootstrap-datepicker?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28148125/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 22:14:07  来源:igfitidea点击:

How to use the bootstrap-datepicker in Django app?

jquerypythondjangotwitter-bootstrapdatepicker

提问by user2962768

I want to use the bootstrap-datepicker (https://bootstrap-datepicker.readthedocs.org) in my django application. I use Django 1.7.

我想在我的 django 应用程序中使用 bootstrap-datepicker ( https://bootstrap-datepicker.readthedocs.org)。我使用 Django 1.7。

In index.html file I have:

在 index.html 文件中,我有:

<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script>
    $(document).ready(function(){
        $('.datepicker').datepicker();
    });
</script>

In my forms.py I have:

在我的 forms.py 中,我有:

class Filter(django_filters.FilterSet):

    class Meta:
        model = MyModel
        fields = ['user', 'date_from', 'date_to']
        widgets = {'date': forms.DateInput(attrs={'class':'datepicker'})}

I my model.py I use to set date:

我用我的 model.py 来设置日期:

date_from = models.DateField()
date_to = models.DateField()

When I'm going through the page with the date - does not work in input area.

当我浏览带有日期的页面时 - 在输入区域中不起作用。

回答by Ellen McCastle

Update: Warning, this suggestion uses the dateTIMEpicker instead of datepicker. I suggested this because you don't have to use the time functionality of the datetimepicker, so it was quite handy in my case.

更新:警告,此建议使用 dateTIMEpicker 而不是 datepicker。我建议这样做是因为您不必使用 datetimepicker 的时间功能,所以在我的情况下它非常方便。

Since I have been trying to get datetimepicker to work (in combination with a model form) for quite some time, I thought I would post the solution, that feels like an accumulation of all stackoverflow posts on this topic ;)

由于我一直试图让 datetimepicker 工作(结合模型表单)很长一段时间,我想我会发布解决方案,感觉就像是关于这个主题的所有 stackoverflow 帖子的积累;)

So, first of all, make sure to also include moment.js, as it is required by bootstrap-datetimepicker (see this stackoverflow post). The order is important, see the mentioned post.

因此,首先,请确保还包含moment.js,因为 bootstrap-datetimepicker 需要它(请参阅此 stackoverflow 帖子)。顺序很重要,请参阅上述帖子。

Then use this siteto get the type of datetimepicker you need. If you have no model form in which you want to embed the datetimepicker, you should be fine with just copying that into your html code.

然后使用此站点获取您需要的日期时间选择器类型。如果您没有想要在其中嵌入日期时间选择器的模型表单,则只需将其复制到您的 html 代码中就可以了。

If you want to make one of your model forms field a fancy datepicker (without time) field like I did, then do the following:

如果你想让你的模型表单字段之一像我一样成为一个花哨的日期选择器(没有时间)字段,然后执行以下操作:

base.html

基本文件

<script type="text/javascript" src="scripts/bootstrap.min.js"></script>
<script type="text/javascript" src="scripts/moment-2.4.0.js"></script>
<script type="text/javascript" src="scripts/bootstrap-datetimepicker.js"></script>

forms.py

表格.py

class MyForm(forms.ModelForm):
    class Meta:
    ...
    widgets = {'myDateField': forms.DateInput(attrs={'id': 'datetimepicker12'})}
    ...

myForm.html:

我的Form.html:

<div class="row">
    ...
    {% bootstrap_form form %}
    ...
</div>
<script type="text/javascript">
    $(function () {
        $('#datetimepicker12').datetimepicker({
            inline: true,
            sideBySide: true,
            format: 'DD.MM.YYYY' /*remove this line if you want to use time as well */
        });
    });
</script>

I hope I was able to save you some time :)

我希望我能够为您节省一些时间:)

回答by Josh_Fokis

I went through similar issue. You need to call the jquery min file before any custom jquery files. so your code would look like this.

我经历了类似的问题。您需要在任何自定义 jquery 文件之前调用 jquery min 文件。所以你的代码看起来像这样。

<link rel="stylesheet" href="{% static 'my_app/css/bootstrap-theme.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/bootstrap.min.css' %}">
<link rel="stylesheet" href="{% static 'my_app/css/datepicker.css' %}">
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<link rel="stylesheet" href="{% static 'my_app/js/bootstrap-datepicker.js' %}">


<script>
$(document).ready(function(){
    $('.datepicker').datepicker();
});
</script>

I know this hasn't been answered in a few months but wanted to post this just to make sure this might help any one else.

我知道这几个月没有得到回答,但想发布这个只是为了确保这可能对其他人有所帮助。

回答by frozenpaw

While there is a python package that seems to solve this quite well I chose to see if I could make the datepicker work using Django's widgetclass to render datepicker attributes, mentioned in the docs.

虽然有一个 python 包似乎很好地解决了这个问题,但我选择看看我是否可以使用 Django 的小部件类来使 datepicker工作以呈现文档中提到的 datepicker 属性。

Note, I am only using a date field and not a date time field because I do not need my app to support times in this instance.

请注意,我只使用日期字段而不是日期时间字段,因为在这种情况下我不需要我的应用程序来支持时间。

models.py

模型.py

class MyModel(models.Model):
    ...
    date = models.DateField()
    ...

forms.py

表格.py

class MyForm(forms.Form):
    ...

    '''
    Here I create a dict of the HTML attributes
    I want to pass to the template.
    '''
    DATEPICKER = {
        'type': 'text',
        'class': 'form-control',
        'id': 'datetimepicker4'
    }
    # Call attrs with form widget
    date = forms.DateField(widget=forms.DateInput(attrs=DATEPICKER))
    ...

template.html

模板.html

<div class="form-group">
  <div class='input-group date' id='datetimepicker1'>
    {{ form.date }}
    <span class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </span>
  </div>
</div>

JS

JS

$(function () {
    $('#datetimepicker1').datetimepicker({
        format: 'YYYY-MM-DD' //This is the default date format Django will accept, it also disables the time in the datepicker.
    })
});

回答by Munim Munna

For DJango version 2.1, 2.0, 1.11, 1.10 and 1.8

对于 DJango 版本 2.1、2.0、1.11、1.10 和 1.8

To use Bootstrap date-picker in your Django app install django-bootstrap-datepicker-plus, follow the installation instructionson the GitHub page to configure it, then you can use it in Custom Forms and Model Forms as below.

要在您的 Django 应用程序中使用 Bootstrap 日期选择器安装django-bootstrap-datepicker-plus,请按照GitHub 页面上的安装说明进行配置,然后您可以在自定义表单和模型表单中使用它,如下所示。

Usage in Custom Forms:

自定义表单中的用法:

from bootstrap_datepicker_plus import DatePickerInput

class ToDoForm(forms.Form):
    user = forms.CharField()
    date_from = forms.DateField(widget = DatePickerInput())

Usage in Model Forms:

在模型表单中的用法

from bootstrap_datepicker_plus import DatePickerInput

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['user', 'date_from', 'date_to']
        widgets = {
            'date_form': DatePickerInput(),
            'date_to': DatePickerInput()
        }

Usage with django-filters:

与 Django 过滤器一起使用:

from bootstrap_datepicker_plus import DatePickerInput

class Filter(django_filters.FilterSet):
   class Meta:
        model = MyModel
        fields = ['user', 'date_from', 'date_to']
        widgets = {'date': DatePickerInput()}

Disclaimer:This django package is maintained by me. For any issues with it please open issueson the Github Page instead of putting comments here.

免责声明:这个 django 包由我维护。对于它的任何问题,请在 Github 页面上打开问题,而不是在此处发表评论。

回答by gccallie

(Django 2.1, 1.11and python >2.7and > 3.4compatible) Working and reusablesolution, custom from bootstrap-datepicker:

Django 2.1、1.11和 python > 2.7和 > 3.4兼容)工作和可重用的解决方案,从bootstrap-datepicker自定义:

import re
from django.conf import settings
from django.utils.translation import get_language
from django import forms
from django.utils import formats, timezone

class BootstrapDatePicker(forms.DateInput):
    format_re = re.compile(r'(?P<part>%[bBdDjmMnyY])')

    def __init__(self, attrs=None, format=None):
        '''
        for a list of useful attributes see:
        http://bootstrap-datepicker.readthedocs.io/en/latest/options.html

        Most options can be provided via data-attributes. An option can be
        converted to a data-attribute by taking its name, replacing each
        uppercase letter with its lowercase equivalent preceded by a dash, and
        prepending "data-date-" to the result. For example, startDate would be
        data-date-start-date, format would be data-date-format, and
        daysOfWeekDisabled would be data-date-days-of-week-disabled.
        '''
        # final_attrs provides:
        # - data-provide: apply datepicker to inline created inputs
        # - data-date-language: apply the current language
        # - data-date-format: apply the current format for dates
        final_attrs = {
            'data-provide': 'datepicker',
            'data-date-language': get_language(),
            'data-date-format': self.get_date_format(format=format),
            'data-date-autoclose': 'true',
            'data-date-clear-btn': 'true',
            'data-date-today-btn': 'linked',
            'data-date-today-highlight': 'true',
        }
        if attrs is not None:
            classes = attrs.get('class', '').split(' ')
            classes.append('datepicker')
            attrs['class'] = ' '.join(classes)
            final_attrs.update(attrs)
        super(BootstrapDatePicker, self).__init__(attrs=final_attrs, format=format)

    def get_date_format(self, format=None):
        format_map = {
            '%d': 'dd',
            '%j': 'd',
            '%m': 'mm',
            '%n': 'm',
            '%y': 'yy',
            '%Y': 'yyyy',
            '%b': 'M',
            '%B': 'MM',
        }
        if format is None:
            format = formats.get_format(self.format_key)[0]
        return re.sub(self.format_re, lambda x: format_map[x.group()], format)

    @property
    def media(self):
        root = 'vendor/bootstrap-datepicker'
        css = {'screen': ('vendor/bootstrap-datepicker/css/bootstrap-datepicker3.min.css',)}
        js = ['%s/js/bootstrap-datepicker.min.js' % root]
        js += ['%s/locales/bootstrap-datepicker.%s.min.js' % (root, lang) for lang, _ in settings.LANGUAGES]
        return forms.Media(js=js, css=css)

Then I implemented my form using BootstrapDatePicker custom class:

然后我使用 BootstrapDatePicker 自定义类实现了我的表单:

class MyModelForm(BootstrapForm, forms.ModelForm):

    class Meta:
        model = myModel
        fields = ('field1', 'field2', 'date')
        widgets = {
            'data': BootstrapDateTimePicker(attrs={'class': 'form-control'}),
        }

Finally I included js/css in the template.

最后我在模板中包含了 js/css。