如何在 Django 的 ModelForm 中使用 DatePicker? [英] How to use a DatePicker in a ModelForm in django?

查看:23
本文介绍了如何在 Django 的 ModelForm 中使用 DatePicker?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 django 3.0 并且我试图在我的 ModelForm 中显示一个日期选择器小部件,但我不知道如何(我只能得到文本字段).我试图寻找一些解决方案,但找不到任何解决方案.这是我的模型和我的 ModelForm 的样子:

I am using django 3.0 and I am trying to display a datepicker widget in my ModelForm, but I can't figure out how (all I can get is text field). I have tried looking for some solutions, but couldn't find any. This is how my Model and my ModelForm look like:

class Membership(models.Model):
  start_date = models.DateField(default=datetime.today, null=True)
  owner = models.ForeignKey(Client, on_delete=models.CASCADE, null=True)
  type = models.ForeignKey(MembershipType, on_delete=models.CASCADE, null=True)

class MembershipForm(ModelForm):
  class Meta:
    model = Membership
    fields = ['owner', 'start_date', 'type']
    widgets = {
        'start_date': forms.DateInput
    }

这是我的 html:

<form class="container" action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>

推荐答案

这是预期的行为.DateInput 小部件 [Django-doc] 只是一个带有可选 format 参数的 元素.

This is the expected behavior. A DateInput widget [Django-doc] is just a <input type="text"> element with an optional format parameter.

您可以使用一个包,例如 django-bootstrap-datepicker-plus [pypi],然后用 DatePickerInput 定义一个表单:

You can make use of a package, like for example django-bootstrap-datepicker-plus [pypi] , and then define a form with the DatePickerInput:

from bootstrap_datepicker_plus import DatePickerInput

class MembershipForm(ModelForm):
  class Meta:
    model = Membership
    fields = ['owner', 'start_date', 'type']
    widgets = {
        'start_date': DatePickerInput
    }

在模板中,您需要渲染表单的媒体并加载引导程序 css 和 javascript:

In the template you will need to render the media of the form and load the bootstrap css and javascript:

{% load bootstrap4 %}
{% bootstrap_css %}
{% bootstrap_javascript jquery='full' %}
{{ form.media }}

<form class="container" action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<button type="submit" class="btn btn-primary">Submit</button>
</form>

这篇关于如何在 Django 的 ModelForm 中使用 DatePicker?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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