我在我的模型中有一个DateTime
字段,我正在寻找一种简单的方法来使它在表单中看起来很好。比如SelectDateWidget
。
我一直在看很多类似的问题,它似乎真的很棘手的东西,如管理日期picker或jquery的工作。(这是我第一次使用Django,我从来没有使用过jquery)。
所以,我从这个例子中使用ChoiceField
代替,但我也不能让它工作。我得到错误名称'self'未定义。这里可以不用self
吗?或者是否有更好的简单的方法来做到这一点?我不需要一个花哨的日期选择器,只需要一些让用户容易输入的东西。
class ProjectForm(ModelForm):
startdate = forms.DateField()
starthour = forms.ChoiceField(choices=((6,"6am"),(7,"7am"),(8,"8am"),(9,"9am"), ...))
startminute = forms.ChoiceField(choices=((0,":00"),(15,":15"),(30,":30"),(45,":45")))
class Meta:
model = Project
def clean(self):
starttime = time(int(self.cleaned_data.get('starthour')),
int(self.cleaned_data.get('startminute')))
return self.cleaned_data
try:
self.instance.start_time = datetime.datetime.combine(
self.cleaned_data.get("startdate"), starttime)
except TypeError:
raise forms.ValidationError("")
forms.py
from django import forms
from django.contrib.admin import widgets
class MyForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['mydate'].widget = widgets.AdminDateWidget()
self.fields['mytime'].widget = widgets.AdminTimeWidget()
self.fields['mydatetime'].widget = widgets.AdminSplitDateTime()
在模板:<script type="text/javascript" src="/my_admin/jsi18n/"></script>
<script type="text/javascript" src="/media/admin/js/core.js"></script>
…或者,对于Django 1.4+:
{% load static %}
<link rel="stylesheet" type="text/css"
href="{% static 'admin/css/forms.css' %} "/>
<link rel="stylesheet" type="text/css"
href="{% static 'admin/css/base.css' %} "/>
<link rel="stylesheet" type="text/css"
href="{% static 'admin/css/global.css' %}"/>
<link rel="stylesheet" type="text/css"
href="{% static 'admin/css/widgets.css' %}"/>
<script type="text/javascript"
src="/admin/jsi18n/"></script>
<script type="text/javascript"
src="{% static 'admin/js/core.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/admin/RelatedObjectLookups.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/jquery.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/jquery.init.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/actions.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/calendar.js' %}"></script>
<script type="text/javascript"
src="{% static 'admin/js/admin/DateTimeShortcuts.js' %}"></script>
如果你被错误所困扰
Could not parse the remainder: '/js/jquery.init.js'' from 'admin/js/jquery.init.js''".
只需在admin/js/jquery.init.js
之前添加一个撇号它看起来像:
'admin/js/jquery.init.js'