Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

django - how to show datepicker calendar on datefield

This is regarding how to use a jQuery date picker in a django powered site.

models.py is

from django.db import models
class holidaytime(models.Model):
    holiday_date = models.DateField()

I am using jquery datepicker.

I am using a model form and created text field for displaying date sucessfully.

But failed to show a datepicker icon. I am using Django model forms.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can use widget to pass a class to the form when it will be rendered in the html. Then that class will be read by javascript to render the datepicker function.

Here is an example:

from django import forms
class HolidayTimeForm(forms.Form):
    holiday_date = forms.DateField(widget=forms.TextInput(attrs=
                                {
                                    'class':'datepicker'
                                }))

... or through the widgets attribute in the Meta class when using ModelForm:

class HolidayTimeForm(forms.ModelForm):

    class Meta:
        model = Holiday
        widgets = {
            'holiday_date': forms.DateInput(attrs={'class':'datepicker'}),
        }

Now in template:

 /* Include the jquery Ui here */
 <script>
  $(function() {
    $( ".datepicker" ).datepicker({
      changeMonth: true,
      changeYear: true,
      yearRange: "1900:2012",
      // You can put more options here.

    });
  });
  </script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...