我的模型中有一个DateTime
字段,我正在寻找一种简单的方法让它在表单中看起来不错。像SelectDateWidget
这样的东西。
我一直在寻找很多类似的问题,让管理员使用像datepicker或jquery这样的东西似乎非常棘手。 (这是我第一次使用Django,之前从未使用过jquery。)
所以,我使用ChoiceField
来代替this示例,但我无法让它工作。我收到错误名称'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("")
答案 0 :(得分:7)
<强> 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>
答案 1 :(得分:2)
如果您遇到错误
Could not parse the remainder: '/js/jquery.init.js'' from 'admin/js/jquery.init.js''".
只需在admin/js/jquery.init.js
之前添加一个apstrophe
它看起来像:
'admin/js/jquery.init.js'