Django 1.8 & Django Crispy Forms: Is there a simple, easy way of implementing a Date Picker?

前端 未结 4 2011
逝去的感伤
逝去的感伤 2021-02-07 13:41

There are an awful lot of date/datetime picker implementations out there. Are there any that integrate with Django and Crispy Forms particularly well, and how are they used?

相关标签:
4条回答
  • 2021-02-07 13:45

    django.forms.SelectDateWidget is simple and flexible:

    date_field = forms.DateField(
        widget=forms.SelectDateWidget(years, months, empty_label)
    )
    

    It even includes its own template file.

    0 讨论(0)
  • 2021-02-07 14:02

    My solution is simple and uses the datetimepicker from https://eonasdan.github.io/bootstrap-datetimepicker/.

    Include the css file:

    <link href="{% static 'css/bootstrap-datetimepicker.min.css' %}" rel="stylesheet">
    

    Include the js files:

    <script src="{% static 'js/jquery-3.1.1.js' %}"></script>
    <script src="{% static 'js/bootstrap.min.js' %}"></script>
    <script src="{% static 'js/moment-master/min/moment.min.js' %}"></script>
    <script src="{% static 'js/bootstrap-datetimepicker.min.js' %}"></script>
    

    Define a css class for the field in the form (works with Crispy too):

    class MyForm(forms.ModelForm):
        class Meta:
            model = MyModelo
            fields =       ['a','b','c']
    
        def __init__(self, *args, **kwargs):
            super(MyForm, self).__init__(*args, **kwargs)
            self.fields['a'].widget.attrs['class'] = 'datepicker'
    

    In the template include a JQuery function linking to the css class:

    <script type="text/javascript">
    $(function () {
        $('.datepicker').datetimepicker(
        {
            format: 'YYYY-MM-DD HH:mm:ss',
            sideBySide: true
        }
        );
    });
    </script>
    

    This solution works great with Django 1.10, Crispy Forms and Django Model Forms.

    0 讨论(0)
  • 2021-02-07 14:09

    Not an answer for a crispy forms but newer browsers will put in a date picker for you as long as the input has an attribute type of date. This falls into the category of minimal development effort.

    date_field = forms.DateField(
        widget=forms.TextInput(     
            attrs={'type': 'date'} 
        )
    )                                           
    
    0 讨论(0)
  • 2021-02-07 14:10

    Easy way is override field template :D

    Field('field_name', template='date.html')
    

    Here gist from @maraujop

    0 讨论(0)
提交回复
热议问题