自定义表单中的 Django 日历小部件 [英] Django calendar widget in a custom form

查看:45
本文介绍了自定义表单中的 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 版本以及您实现表单字段的方式.这就是我发现我需要使用小部件的原因.

现在只需像平常一样输出您的表单,JS 就会自动将其转换为日期字段.享受!

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

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

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