如何在django表单上为日期选择器字段分配唯一ID?

问题描述 投票:0回答:1

我正在使用django-bootstrap3pip install django-bootstrap3)第三方应用程序来呈现表单。我正在使用django-bootstrap-datepickerpip install django-bootstrap-datepicker)应用程序来应用小部件日历。

在下面的表格中,我有两个字段:check_incheck_out,我想将日期选择器应用于一起

from bootstrap_datepicker.widgets import DatePicker
class DateInput(DatePicker):
    def __init__(self):
        DatePicker.__init__(self,format="%Y-%m-%d")
    def build_attrs(self, attrs, extra_attrs=None, **kwargs):
        attrs = dict(self.attrs, **kwargs)
        if extra_attrs:
            attrs.update(extra_attrs)
        return attrs

class LodgingOfferForm(forms.ModelForm):

    class Meta:
        widgets = {
            'check_in': DateInput(),
            'check_out': DateInput(),
        }
        model = LodgingOffer
        fields = ('other fields', 'check_in', 'check_out', )

在html模板上,我正在渲染这种形式,包括form.media接受bootstrap-datepicker的js和css效果:

{% load bootstrap3 %}
{% block body_content %}

{% block extrahead %}   {# Extra Resources Start #}
   {{ form.media }}        {# Form required JS and CSS #}
{% endblock %}

{% bootstrap_field form.check_in %}
{% bootstrap_field form.check_out %}
{% endblock %}

当我尝试渲染我的表单时,日期选择器效果仅适用于表单中呈现的第一个字段,这意味着正好check_in字段具有日期选择器效果而check_out字段没有它。

  • 登记入住

enter image description here

  • 退房

enter image description here

UPDATE

我在浏览器中执行检查,发现check_incheck_out字段具有相同的id _pickers和JS代码调用找到的第一个_pickers

  • 入住enter image description here
  • 看看enter image description here

如何修改每个字段的id,并将to widget命令合在一起工作?

django datepicker bootstrap-datepicker
1个回答
1
投票

我用这种方式更改了id pickers

class LodgingOfferForm(forms.ModelForm):
    class Meta:
        widgets = {
            'check_in': DateInput(),
            'check_out': forms.DateInput(attrs={'id': 'datepicker2'}),

            'country': CountrySelectWidget(),
        }
        model = LodgingOffer
        fields = ('check_in', 'check_out', )

在我的模板中,我以这种方式覆盖或调用datepicker函数:

<script type="text/javascript">
        $(function () {
        $('#datepicker2').datepicker({
            inline: true,
            sideBySide: true,
           // format: 'DD.MM.YYYY' 
        });
    });
    </script>

通过这种方式,我可以看到不同的ID和我的日历选择器在一起的字段中工作

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.