首页 > 解决方案 > 如何将日期/日历小部件添加到 django 表单?

问题描述

我尝试关注这些链接但这没有用。该小部件未在表单中加载,并且 js 文件在控制台中给出 404 错误,而它可以从链接访问。我使用酥脆的表格来呈现我的表格。

表格.py

       DateInput = partial(forms.DateInput, {'class': 'datepicker'})

    # patient Form
    class PatientForm(ModelForm):

        birth_date = forms.DateField(label='Birth Date',widget=DateInput())
        class Meta:
            model = Patient
            exclude = ['user',]

模板

           <h2>Add Patient</h2>
            <form method="POST" action="{% url 'patients:patient_create' %}">

                {% csrf_token %}
                 {{ form|crispy }}
                <button type="submit" class="btn btn-primary" >Add Patients</button>
                <p></p>
            </form>
</div>
    {% endblock %}

    <script>
    $(document).ready(function() {
        $('.datepicker').datepicker();
    });
    </script>

js文件+CSS的链接

<script src=”https://code.jquery.com/jquery-1.12.4.js”&gt;</script>
<script src=”https://code.jquery.com/ui/1.12.1/jquery-ui.js”&gt;</script>
<link rel=”stylesheet” href=”//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css”&gt;

控制台中的错误

Not Found: /patients/”https://code.jquery.com/jquery-1.12.4.js”
Not Found: /patients/”https://code.jquery.com/ui/1.12.1/jquery-ui.js”
[18/Jul/2019 15:29:09] "GET /patients/%E2%80%9Dhttps://code.jquery.com/jquery-1.12.4.js%E2%80%9D HTTP/1.1" 404 6742
[18/Jul/2019 15:29:09] "GET /patients/%E2%80%9Dhttps://code.jquery.com/ui/1.12.1/jquery-ui.js%E2%80%9D HTTP/1.1" 404 6760
Not Found: /patients/”https://code.jquery.com/jquery-1.12.4.js”
[18/Jul/2019 15:29:10] "GET /patients/%E2%80%9Dhttps://code.jquery.com/jquery-1.12.4.js%E2%80%9D HTTP/1.1" 404 6742
Not Found: /patients/”https://code.jquery.com/ui/1.12.1/jquery-ui.js”
[18/Jul/2019 15:29:10] "GET /patients/%E2%80%9Dhttps://code.jquery.com/ui/1.12.1/jquery-ui.js%E2%80%9D HTTP/1.1" 404 6760
Not Found: /favicon.ico

在我的代码中,我有很多 jquery 版本会导致问题。我想要一个比 jquery ui 更用户友好的小部件,那么有没有其他方法可以用来添加与 jquery ui 相同的小部件?

标签: javascriptdjangodjango-formsdjango-templatesdjango-views

解决方案


在您的 forms.py 中:

class DateInput(forms.DateInput):
     input_type = 'date'

class PatientForm(ModelForm):


        class Meta:
            model = Patient
            exclude = ['user',]
            widgets = {
                'birth_date':DateInput,
               }

尝试这个


推荐阅读