DateTimePicker with Django Crispy Forms

廉价感情. 提交于 2021-02-08 08:19:35

问题


I am using Python3, Django 1.5 and Bootstrap 3.

I have a model with a DateTimeField object, and for the form related to that model, I want to use a DateTimePicker widget from here: http://www.malot.fr/bootstrap-datetimepicker/

The html for this widget should be:

  <div id="div_id_start_time" class="form-group">
    <label for="id_start_time" class="control-label col-lg-2">Start Time</label>
    <div class="col-lg-5 input-append input-group date form_datetime"
       data-date-format="dd MM yyyy - HH:ii P" data-link-field="id_start_time">
      <input class="form-control" size="16" type="text" value="" readonly>
      <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
      <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
    </div>
    <input type="hidden" id="id_start_time" value="" /><br/>
  </div>
</fieldset>

I'm trying to use crispy forms, but I'm having trouble getting it to make this particular output. I have a feeling I need to create my own layout object for this widget, but I'm not sure how to go about doing that, the docs are a little thin on this subject.

Any ideas?


回答1:


What I ended up doing was to just create a template for this widget. So the code looks like this:

datetimefield.html

{% load crispy_forms_field %}

<div{% if div.css_id %} id="{{ div.css_id }}"{% endif %} class="form-group{% if form_show_errors and field.errors %} has-error{% endif %}{% if field.css_classes %} {{ field.css_classes }}{% endif %}{% if div.css_class %} {{ div.css_class }}{% endif %}">
    {% if field.label and form_show_labels %}
        <label for="{{ field.id_for_label }}" class="control-label {{ label_class }}{% if field.field.required %} requiredField{% endif %}">
            {{ field.label|safe }}{% if field.field.required %}<span class="asteriskField">*</span>{% endif %}
        </label>
    {% endif %}

  <div class="controls input-group input-append date form-datetime col-md-5" data-link-field="{{ field.id_for_label }}" {{ flat_attrs|safe }}>
    <input class="form-control" size="16" type="text" value="" readonly>
    <span class="input-group-addon"><span class="glyphicon glyphicon-remove"></span></span>
    <span class="input-group-addon"><span class="glyphicon glyphicon-th"></span></span>
  </div>
  <input type="hidden" id="{{ field.id_for_label }}" value="" /><br/>
  {% include 'bootstrap3/layout/help_text_and_errors.html' %}
</div>

forms.py

    self.helper.layout = Layout(
        Field('start_time', template="layout/datetimefield.html", data_date_format="dd MM yyyy - HH:ii P"),
    )   


来源:https://stackoverflow.com/questions/19865120/datetimepicker-with-django-crispy-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!