Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
463 views
in Technique[技术] by (71.8m points)

jquery - How to use Datepicker in django

I want to implement a django form with datepicker. I made my 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'
                                })) 

and 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>

And still there is no datepicker in my input box of that form. I also tried with including my files link in the script as in my balance.html

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

still the datepicker is not working. But when including jquery in my html file, it also makes not to work jquery-treetable which I have implemented in my html file.

How to make the datepicker work ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use forms.DateInput() widget, instead of 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())

To make JQuery Datepicker work, you have to initialise it:

<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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...