如何为Django管理员创建自定义日期时间小部件? [英] How to create a custom date time widget for the django admin?
问题描述
我的问题:
我有一个接受DateTimeField
的模型.用户从django-admin
输入.但是,我无法获取用户的本地时区.因此,我最好的选择是强制用户在UTC
中输入日期时间.但是为了方便用户,我不希望他/她每次都计算偏移量,然后再计算UTC
中的时间. Django
似乎没有提供执行此操作的方法.
I have a model that accepts DateTimeField
. The user enters this from the django-admin
. But, I cant get a way to get the user's local timezone. So my best shot is forcing the user to enter the date-time in UTC
. But for the users convenience, I do not want him/her to calculate each time the offset and then the time in UTC
. Django
doesn't seem to provide a way of doing this.
我打算做什么:
我想创建一个custom widget
,同时允许用户选择timezone
并输入date
和time
.为此,我正在使用jQuery datetime picker.
我也打算override
django admin
表单使其使用我的这个小部件.
I want to create a custom widget
that will also let the user choose the timezone
along with entering the date
and time
. For this I am using the jQuery datetime picker.
I also intend to override
the django admin
form to have it use this widget of mine.
到目前为止,我已经尝试过:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> - jsFiddle demo by ioncache</title>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<link rel="stylesheet" type="text/css" href="/css/normalize.css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="/css/result-light.css">
<script type='text/javascript' src="https://raw.github.com/trentrichardson/jQuery-Timepicker-Addon/master/jquery-ui-timepicker-addon.js"></script>
<link rel="stylesheet" type="text/css" href="https://raw.github.com/trentrichardson/jQuery-Timepicker-Addon/master/jquery-ui-timepicker-addon.css">
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/smoothness/jquery-ui.css">
<style type='text/css'>
</style>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
$(function() {
$('#date-time-tz').datetimepicker({
dateFormat: $.datepicker.RFC_2822,
timeFormat: 'hh:mm:ss z',
showTimezone: true,
timezoneList: [
{"value": "0", "label": "UTC"},
{"value": "+60", "label": "FRANCE"},
{"value": "+330", "label": "INDIA"},
{"value": "-240", "label": "US EAST"},
{"value": "-420", "label": "US SF"}
]
});
});
});//]]>
</script>
</head>
<body>
<form name="time">
<div style="margin: 15px;">
<input id="date-time-tz" type="text" value="" name="date-time-tz">
<input type="submit" value="Submit">
</div>
</form>
</body>
</html>
没有任何action
或method
,因为我不希望此小部件在任何地方post
进行任何操作.它所做的只是在浏览器中显示一个漂亮的UI
,并允许用户输入date-time
和timezone
.因此,当用户单击此jQuery UI
中的Done
时,该值将出现在form.
There isnt any action
or method
because I don't want this widget to post
anything anywhere. What it simply does is brings out a nice UI
in the browser and lets the user enter a date-time
and timezone
. So when the user clicks on Done
in this jQuery UI
the value appears in the textbox
of the form.
我似乎被挡住了.无法完全考虑:
无论如何,我都无法通过widgets.py
文件中的id
或name
让我reference
这个input
. widgets.py
文件是我打算通过从*django.forms.widgets*
扩展Widget
来define
custom widget
的文件.我通读了 docs 并弄清楚了在这种情况下,Widget
类具有两种特别重要的方法. render
和value_from_data_dict
方法.前者呈现html模板,而后者则从数据字典中提取该值. (我可能错了.)但是我无法找到任何方法来链接我的代码的这两部分.我需要帮助.
I cant figure out anyway that will let me reference
this input
by its id
or name
inside my widgets.py
file. widgets.py
file is the file where I intend to define
the custom widget
by extending Widget
from *django.forms.widgets*
. I read through the docs and figured out that Widget
class has two methods of particular importance in this case. The render
and value_from_data_dict
methods. The former to render the html template and the latter to extract that value from the data dict. (I may be wrong.) But I cant figure out any way to link these two parts of my code. I need help.
更新:
我在处理它,但是没有用.到目前为止,我一直在做以下事情:
I worked on it but its not working. Heres what I have done till now:
ui/admin.py
class MyModelAdmin(admin.ModelAdmin):
class Media:
css = {
"all": ("style/jquery-ui.css",
"style/jquery-ui-timepicker-addon.css",)
}
js = ("js/jquery-ui.js",
"js/jquery-ui-timepicker-addon.js",
"js/tz_widget.js",)
formfield_overrides = {
models.DateTimeField : {'widget': TimezoneDate()},
}
widgets.py
DATE_FORMAT = "%m-%d-%y"
class TimezoneDate(forms.widgets.Widget):
def __init__(self, attrs=None):
super(TimezoneDate, self).__init__(attrs)
def render(self, name, value, attrs=None):
if value is None:
vstr = ''
elif hasattr(value, 'strftime'):
vstr = datetime_safe.new_datetime(value).stftime(DATE_FORMAT)
else:
vstr = value
id = "%s" % name
args = \
"<input type=\"text\" value=\"%s\" name=\"%s\" id=\"date_time_tz\" />" % \
(vstr, name)
return mark_safe(u"\n".join(args))
这是 tz_widget.js:
$(window).load(function(){
$(function() {
$('#date-time-tz').datetimepicker({
dateFormat: $.datepicker.RFC_2822,
timeFormat: 'hh:mm:ss z',
showTimezone: true,
timezoneList: [
{"value": "0", "label": "UTC"},
{"value": "+60", "label": "FRANCE"},
{"value": "+330", "label": "INDIA"},
{"value": "-240", "label": "US EAST"},
{"value": "-420", "label": "US SF"}
]
});
});
});
我被困的是如何从tz_widget.js调用javascript?在django管理员中,没有下拉列表或其他任何内容.因此,我确定不会调用javascript函数.我怎么称呼它?我不认为我可以沿html unicode字符串呈现它.有任何想法吗?我整晚都在这.请需要帮助.
What I am stuck at is how do I invoke the javascript from tz_widget.js? In the django admin there is no dropdown or anything. So I am sure the javascript function isnt being called. How can I call it? I dont think I can render it along the html unicode string. Any ideas? I have been at this all night. Need some help please.
推荐答案
我认为您可以创建一个更通用的小部件.
I think you can create a more generic widget.
首先,将您的js,html和媒体分开以创建唯一的小部件.
First, separate your js, html and media for create a unique widget.
widgets.py
widgets.py
class DatTimeField(forms.Textarea):
def render(self, name, attrs = None):
final_attrs = self.build_attrs(attrs,name=name)
return "Here you have to return the html of your widget, for example: mark_safe(u'<input type=text %s value=%s class='your_css_class'/>' % (flatatt(final_attrs), value))"
现在在您的管理类中,尝试以下操作:
Now in your admin class, try this:
class YourClassAdmin(admin.ModelAdmin):
class Media:
css = {
"all": ("my_styles.css",)
}
js = ("my_code.js",)
formfield_overrides = {
models.DateTimeField : {'widget': DatTimeField()},
}
如果要自定义窗口小部件,建议您查看TinyMce窗口小部件代码.我知道这是一种不同的方式,但是这段代码帮助我开发了自己的小部件( https://github.com/aljosa/django-tinymce/tree/master/tinymce )
If you want to customize your widgets, I suggest you to see the TinyMce widget Code. I know it's a way different but this code helped me to develop my own widgets (https://github.com/aljosa/django-tinymce/tree/master/tinymce)
Django文档也很有帮助: https://docs.djangoproject.com/en/1.5/ref/forms/widgets/
Django docs is also helpful: https://docs.djangoproject.com/en/1.5/ref/forms/widgets/
这篇关于如何为Django管理员创建自定义日期时间小部件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!