一尘不染

如何在Django中使用Datepicker

django

我想用datepicker实现django表单。我做了我的forms.py

from django import forms

class DateRangeForm(forms.Form):
    start_date = forms.DateField(widget=forms.TextInput(attrs=
                                {
                                    'class':'datepicker'
                                }))
    end_date = forms.DateField(widget=forms.TextInput(attrs=
                                {
                                    'class':'datepicker'
                                })) 

views.py

if request.method == "POST":
        f = DateRangeForm(request.POST)
        if f.is_valid():
            c = f.save(commit = False)
            c.end_date = timezone.now()
            c.save()
    else:
        f = DateRangeForm()
        args = {}
        args.update(csrf(request))
        args['form'] = f


    return render(request, 'trial_balance.html', {
        'form': f
    })

balance.html

<div>
    <form action="" method="POST"> {% csrf_token %}
    Start Date:{{ form.start_date }}&nbsp;&nbsp; End Date:{{ form.end_date }}<br/>
    <input  type = "submit" name = "submit" value = "See Results">
    </form>

</div>

而且在该表格的输入框中仍然没有日期选择器。我也尝试像在balance.html中一样在脚本中包含文件链接

<script src="{{ STATIC_URL }}js/jquery-1.3.2.min.js"></script>

datepicker仍然无法正常工作。但是,当在我的html文件中包含jquery时,这也使得我在我的html文件中实现的jquery-treetable无法工作。

如何使日期选择器工作?


阅读 853

收藏
2020-04-02

共1个答案

一尘不染

你可以使用forms.DateInput()小部件,而不是forms.TextInput()

from functools import partial
DateInput = partial(forms.DateInput, {'class': 'datepicker'})

class DateRangeForm(forms.Form):
    start_date = forms.DateField(widget=DateInput())
    end_date = forms.DateField(widget=DateInput())

要使JQuery Datepicker起作用,必须对其进行初始化:

<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.0/themes/smoothness/jquery-ui.css"> 
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function() {
    $('.datepicker').datepicker();
});
</script>
2020-04-02