Django日历小部件在自定义窗体中 [英] Django calendar widget in a custom form

查看:170
本文介绍了Django日历小部件在自定义窗体中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为我的一种表单添加日历日期输入。 Django在其管理页面上使用了一个精彩的日历小工具,但我无法弄清楚如何将其添加到自定义窗体中。

I am trying to add a calendar date input to one of my forms. There is a wonderful calendar widget that Django uses on its admin pages, but I can't figure out how to add it to a custom form.

我发现了一对其他关于同一主题的问题在这里,但他们都似乎已经过时,复杂和不工作。

I found a couple other questions about the same subject here, but they all seemed to be out of date, complicated, and not working.

有没有办法将Django内置的日历小工具我的一个表格?

Is there a way to include Django's built in calendar widget into one of my forms?

推荐答案

我想出来,感谢Dave S.和一些关于这个话题的老帖子。我的成功方法:

I figured it out, thanks to Dave S. and a number of old posts on this topic. My successful method:

在顶部,使用 from django.contrib.admin.widgets import AdminDateWidget 。然后,只要您想使用日期窗口小部件,请使用 my_field = DateField(widget = AdminDateWidget)添加窗体的不同字段。

At the top, import the admin widgets using from django.contrib.admin.widgets import AdminDateWidget. Then, add the different fields of your form, using my_field = DateField(widget = AdminDateWidget) whenever you want to use the date widget.

将以下内容放在顶部,以包含适当的css / js文件:

Place the following toward the top to include the appropriate css/js files:

{% load i18n admin_modify adminmedia %}
{% block extrahead %}{{ block.super }}
<link rel="stylesheet" type="text/css" href="{% admin_media_prefix %}css/base.css" />
<link rel="stylesheet" type="text/css" href="{% admin_media_prefix %}css/widgets.css" />
<script type="text/javascript" src="/jsi18n/"></script>
<script type="text/javascript" src="{% admin_media_prefix %}js/core.js"></script>
{{ form.media }}
{% endblock %}

<注意:您不一定需要所有这些,具体取决于您的Django版本以及您如何实现表单域。这就是我发现我需要使用这些小部件。

Note: You do not necessarily need all of this, depending upon your version of Django and how you are implementing the form fields. this is what I found that I needed to use the widgets.

现在只需输出正常的格式,JS应该自动将其转换为日期领域。享受!

Now just output your form like normal, and the JS should automatically convert it to a date field. Enjoy!

这篇关于Django日历小部件在自定义窗体中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆