ModelForm中定制datetimepicker插件

利用ModelForm生成前端页面中,DateField字段会默认生成TextInput款, 这样用户的输入不好控制时间格式,所以利用datetimepicker控制用户的输入非常有必要,如何将datetimepicker融入到ModelForm生成的前端页面中?

最终效果

datetimepicker的基本使用

  1. 导入插件的css、 js和locales文件
  2. 导入html文件
  3. 编写js代码,配置datetimepicker参数

与ModelForm生成的input框结合

我们在前端页面中看源码可以发现,默认的DateField字段生成的是一个TextInput框,在forms.TextInput中我们可以看到

那我们根据template_name的路径去找到text.html

django/forms/widgets/text.html

{% include "django/forms/widgets/input.html" %}

text.html指向了input.html

django/forms/widgets/input.html

<input type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}{% include "django/forms/widgets/attrs.html" %} />

我们通过源码知道,ModelForm中显示input框是根据这段代码

思路: 通过自己编写一个类,将template_name地址指向我们编写的html文件, 文件中放入我们datetimepicker的html代码


编写一个datetimepicker类

from django import forms


class DateTimePickerInput(forms.TextInput):  #继承forms.TextInput类
    template_name = 'stark/forms/widgets/datetime_picker.html'  #重写template_name地址,将地址指向我们自己写的html文件

stark/forms/widgets/datetime_picker.html

<div class="input-group date form_date">
    <input class="form-control" size="16" type="text" value="" readonly>
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
</div>

到这里,我们就成功的将ModelForm显示的DateField字段设定成我们想要的样式,但是还要注意一点,默认的TextInput款的html文件中的input对象,还有很多参数,所以我们要把那些参数和我们插件的html代码结合,这样才能保证不影响ModelForm的其他功能

最终:

stark/forms/widgets/datetime_picker.html

<div class="input-group date form_date">
    <input class="form-control" readonly type="{{ widget.type }}" name="{{ widget.name }}"{% if widget.value != None %} value="{{ widget.value|stringformat:'s' }}"{% endif %}{% include "django/forms/widgets/attrs.html" %} />
    <span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span></span>
</div>
原文地址:https://www.cnblogs.com/aaaajayheng1990/p/11048359.html