将日期时间的文本条目替换为 Django 表单中的日历日期选择器图标

我的 Django 应用程序中有这个模板,用于添加培训课程:


{% extends 'base.html' %}


{% load crispy_forms_tags %}


{% block content %}

    <h1>New session</h1>

    <form action="" method="post">{% csrf_token %}

        {{ form|crispy }}

        <input class="btn btn-success" type="submit" value="Save" />

    </form>

    <p />

{% endblock content %}

该表单包含一个日期时间字段,如下所示:

http://img1.mukewang.com/63b4efb30001b48904230157.jpg

是否可以更改此设置,而不是将日期时间作为文本输入,而是可以从日历类型图标中选择?如果是这样,这是怎么做到的?


这是我的观点:


class SessionCreateView(CreateView):

    model = ClubSession

    template_name = 'session_new.html'

    fields = ['location', 'coach', 'date', 'details']

这是我的模型:


class ClubSession(models.Model):

    location = models.CharField(max_length=200)

    coach = models.ForeignKey(CustomUser, on_delete=models.CASCADE)

    date = models.DateTimeField(default=now)

    details = models.TextField()


    def __str__(self):

        return self.location


    def get_absolute_url(self):

        return reverse('session_detail', args=[str(self.id)])


达令说
浏览 83回答 1
1回答

Cats萌萌

使用脆皮表格,我认为您需要一个表格。class ClubSessionForm(forms.ModelForm):&nbsp; &nbsp; class Meta:&nbsp; &nbsp; &nbsp; &nbsp; model = ClubSession&nbsp; &nbsp; &nbsp; &nbsp; fields = ['location', 'coach', 'date', 'details']&nbsp; &nbsp; def __init__(self, *args, **kwargs):&nbsp; &nbsp; &nbsp; &nbsp; super().__init__(*args, **kwargs)&nbsp; &nbsp; &nbsp; &nbsp; self.fields['date'].widget.attrs.update({'type': 'datetime-local'})class SessionCreateView(CreateView):&nbsp; &nbsp; model = ClubSession&nbsp; &nbsp; form_class = ClubSessionForm&nbsp; &nbsp; template_name = 'session_new.html'文档请记住,并非所有浏览器都支持<input type="datetime-local">——我相信只有 Chrome 和 Opera 支持。如果您需要它在所有浏览器中工作,您将需要一个 JS 解决方案。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python