django管理日期时间小部件(日历)在自定义表单中

时间:2014-10-18 17:59:47

标签: python django calendar widget

我无法在表单中添加管理日历窗口小部件。怎么做?

model.py

from django.db import models
from django.contrib.auth.models import User


FIELDNUM = (('1', '1'), ('2', '2'), ('3', '3'),
            ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'),
            ('9', '9'), ('10', '10'))

FIELDNAMES = (('test', 'test'), ('kostas', 'kostas'), ('kaka', 'kaka'))

class Reservation(models.Model):
    field_name = models.CharField("Field Name*", choices=FIELDNAMES, max_length=100)
    fieldnum = models.CharField("Field Number*", choices=FIELDNUM, max_length=2)
    date = models.DateField("Date*")
    time = models.TimeField("Time*")
    user = models.ForeignKey(User)
    date_time = models.DateTimeField(auto_now_add=True, blank=True, unique=False)

    def __unicode__(self):
        return '%s, %s, %s, %s' % (self.field_name, self.date, self.time, self.date_time)

    class Meta:
        unique_together = ("field_name", "fieldnum", "date", "time")

form.py

from django import forms
from booking.models import Reservation

class ReservationForm(forms.ModelForm):
    class Meta:
        model = Reservation
        exclude = ['user']

我在表格中将表单渲染为段落。

在哪里调用窗口小部件以及如何在我的模板中设置它以使其工作?

1 个答案:

答案 0 :(得分:0)

我认为最简单的方法是不使用django.contrib.admin.widgets中的小部件,而是使用第三方小部件,例如来自jQuery UI的Datepicker

您所要做的就是在模板中加入jQuery UI并添加此脚本

<script>
  $(function() {
    $( ".date_picker" ).datepicker();
  });
</script>

其中.date_picker是与date模型的Reservation字段相关的表单输入类的名称。

为了让Django将此class='date_picker'添加到与date相关的生成表单输入中,您必须稍微修改一下ModelForm。更具体地说,

from django import forms
from booking.models import Reservation

class ReservationForm(forms.ModelForm):
    class Meta:
        model = Reservation
        exclude = ['user']
        widgets = {
            'date' : forms.DateInput(attrs={'class' : 'date_picker'})
        }

当您在模板中调用<input type='text' ... class='date_picker' />时,这会产生{{ form.as_p }}的效果,而jQuery UI会完成剩下的工作。

顺便说一句,对models.py的一个小改进是使用python的列表理解。即

FIELDNUM = (('1', '1'), ('2', '2'), ('3', '3'),
        ('4', '4'), ('5', '5'), ('6', '6'), ('7', '7'), ('8', '8'),
        ('9', '9'), ('10', '10'))

相当于

FIELDNUM = [(str(i), str(i)) for i in range(1,11)]