【问题标题】:How to add a datepicker to django forms [closed]如何将日期选择器添加到 django 表单 [关闭]
【发布时间】:2016-11-19 13:36:18
【问题描述】:

Django 不支持其表单的日期选择器,我没有找到任何适合我的解决方案。

如果有人知道一些简单的解决方案,我将非常感激。

谢谢。

forms.py

    class meta:
        model = Student
        fields = ["classfk","name","birth_date"]

views.py

class CreateNewStudent(CreateView):
    fields = ("classfk","name", "birth_date")
    model = Student
    success_url = '/class/'
    template_name = "temp/newstudent.html"

newstudent.html

<html>
<body>
<head>

</head>

<form action="" method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <input type="submit"/>
</form>

</body>
</html>

【问题讨论】:

  • PS:我对 Django 表单一无所知,但我能够找到它。这是出现在 Google 搜索中的第一个链接
  • 这个链接的这个答案不能解决问题
  • 没有解决问题是什么意思?您会遇到一些错误/异常/意外行为吗?我什至不知道你尝试了什么。请与问题一起提及所有必要的信息。只有这样来自 SO 的人才能帮助您:)
  • 我只是编辑我的答案。你可以检查一下

标签: python django django-forms


【解决方案1】:

以您的示例为例,您的表单应如下所示:

class DateForm(ModelForm):
  class Meta:
    model = Student
    fields = ["classfk","name","birth_date"]

你的view.py:

class CreateNewStudent(CreateView):
  fields = ("classfk","name", "birth_date")
  model = Student
  success_url = '/class/'
  template_name = "temp/newstudent.html"

和你的模板:

<head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
        <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script>
                $(function() {
                        $( "#id_birth_date" ).datepicker({
                                dateFormat: "yy-mm-dd",
                                defaultDate: "+1w",
                                changeMonth: true,
                                numberOfMonths: 2,
                                onClose: function( selectedDate ) {
                                        $( "#id_birth_date" ).datepicker( "option", "minDate", selectedDate );
                                }
                        });
                });
        </script>

<head>
<body>
<form action="" method="post">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Save" />
</form>
</body>

您可以根据jQuery UI文档http://api.jqueryui.com/datepicker/自定义日期选择器

【讨论】:

  • 我的视图是基于类的视图,class CreateNewStudent(CreateView):fields = ("classfk","name", "birth_date") model = Student success_url = '/class/' template_name = " temp/newstudent.html”会怎样?谢谢你的回答。
  • 更新您的帖子。编写你的 view.py、form.py 和模板
  • 我从文件中添加了一些代码,以便更容易。
猜你喜欢
  • 2021-09-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多