bga*_*ial 9 javascript django datepicker django-forms bootstrap-datepicker
当我根据这个答案尝试渲染django-bootstrap-datepicker-plus小部件时,我有些不便.一切正常,但Datepicker没有出现.
我的Django版本是1.10.7,我使用的第三方应用程序是:
pip install django-bootstrap3)pip install django-bootstrap-datepicker-plus)这是我的forms.py,我DateInput根据我的需要覆盖类来定制它.
from django import forms
from bootstrap_datepicker.widgets import DatePicker
class DateInput(DatePicker):
    def __init__(self):
        DatePicker.__init__(self,format="%Y-%m-%d")
class UserUpdateForm(forms.ModelForm):
    class Meta:
        widgets = {     
            'date_of_birth': DateInput(),  # datepicker
            'creation_date': DateInput(), # datepicker
        }
        fields = ("other fields", "date_of_birth", "creation_date", "other fields",)
        model = get_user_model()
然后在我的模板表单中,我有一些名为layout.htmlMy template的基本主模板,我user_form.html希望在其中呈现前面提到的表单字段.所有这个模板都有一些div和html结构,你可以在这里看到user_form.html文件.
在我的settings.py的bootstrap设置中,我必须include_jquery选择True
当我转到表单页面时,date_of_birth字段不会呈现为日历日期选择器,这将呈现为输入类型文本,其中用户应手动并以特定格式输入日期.
在我的layout.html中,我将一些额外的cdn jQuery资源调用到另一个东西.
[以下评论比此编辑更早]
尝试在 base.html 模板中添加这些链接标签,并从它扩展到 html 模板表单:
<link href="//cdn.bootcss.com/bootstrap-datetimepicker/4.17.44/css/bootstrap-datetimepicker.min.css" rel="stylesheet">
<script src="//cdn.bootcss.com/jquery/3.0.0/jquery.min.js"></script>
<script src="//cdn.bootcss.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//cdn.bootcss.com/moment.js/2.17.1/moment.min.js"></script>
并添加 {{ form.media }} 到您的模板表单中,例如:
      <form class="mt-3" action="" method="post">{% csrf_token %}
          {{ form.as_p }}
          {{ form.media }}
          <div class="text-center">
            <input class="btn btn-primary btn-block" type="submit" value="Update" />
          </div>
      </form>
这解决了我的 django-bootstrap-datepicker-plus 问题。该软件包需要更详细的文档,简单且带有示例。但是一旦你开始配置它,它就会工作得很好。
您正在使用django-bootstrap-datepicker-plus,它适用于 DJango 版本 >= 1.8,因此它应该可以在您使用 DJango 版本 1.10.7 的项目上完美运行。如果您按照安装页面的说明正确执行了所有操作,您可能需要查看以下清单以查看所有内容是否都已就位。
小部件正常工作的清单
include_jquery中将选项设置为。True   {% load bootstrap3 %}       {# imports bootstrap3 #}
   {% bootstrap_css %}         {# Embeds Bootstrap CSS #}
   {% bootstrap_javascript %}  {# Embeds Bootstrap JS #}
   {% block extrahead %}       {# Embeds Extra Resources #}
   {% endblock %}              {# Ends Extra Resources #}
   {% block extrahead %}   {# Extra Resources Start #}
   {{ form.media }}        {# Form required JS and CSS #}
   {% endblock %}          {# Extra Resources End #}
更新:发现错误
问题正是你所猜测的那样。“在我的layout.html中,我将一些额外的cdn jQuery资源调用到其他东西。这会导致任何冲突吗?”
我浏览了你的layout.html内容,发现其中包含 2 个 jQuery 库,一个位于第 22 行,另一个位于第 #299 行,并且你说你已将include_jquery选项设置为true. 所以是的,它们是冲突的。日期选择器绑定到由 bootstrap option 加载的 jQuery include_jquery,并且该 jQuery 被第 #299 行中的 jQuery 覆盖。
解决方案:
解决方案是在模板中仅保留一个 jQuery。摆脱模板中的所有 jQuery,只include_jquery保留true. 或者仅在主模板的标头中保留一个 jQuery,位于任何其他脚本之前,并将其设置include_jquery为false.