3

我的模型中有一个DateTime字段,我正在寻找一种简单的方法让它在表单中看起来不错。类似的东西SelectDateWidget

我一直在研究很多类似的问题,让管理员 datepicker 或 jquery 之类的东西工作似乎真的很棘手。(这是我第一次使用 Django,之前从未使用过 jquery)。

所以,我在这个ChoiceField例子中使用了,但我也无法让它工作。我得到错误名称'self' is not defined。我不能在这里使用吗?还是有更好的简单方法来做到这一点?我不需要花哨的日期选择器,只需要让用户轻松输入的东西。 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("")
4

2 回答 2

7

表格.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>
于 2013-03-08T10:45:46.770 回答
2

如果您遇到错误

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' 
于 2016-04-21T14:57:10.237 回答