【问题标题】:Django widgets and date fieldsDjango 小部件和日期字段
【发布时间】:2023-04-06 11:52:01
【问题描述】:

在我的创建模板中,日期字段呈现为 CharField 并且不允许选择日期,而我需要此验证日期。

我的模型包含一个 DateField :

class Interview(models.Model):
     date_planned = models.DateField(verbose_name="Planned Date", blank=True, null=True)

我的视图调用 ModelForm 很正常:

class InterviewCreateView(UserAccessMixin, CreateView):
    permission_required = "interviews.add_interview"
    model = Interview
    form_class = InterviewForm
    fields = ['date_planned', 'topics']
    template_name = "interviews/interview_create_form.html"
    success_url = reverse_lazy("interviews:interviews_list")
    ```
 My Form just calls the Meta and includes a widget:

类 InterviewForm(ModelForm): def init(self, *args, **kwargs): super().init(*args, **kwargs) self.fields['date_planned'].widget.attrs.update({'size': 40, 'type': 'date'})

class Meta:
    model = Interview
    fields=['topics', 'date_planned']```

确实,输入字段的大小达到了 40,但是系统忽略了日期格式,并让我的 date_planned 字段显示为 CharField

【问题讨论】:

  • 你有什么问题?
  • 我的问题是 DateInput 在处理表单时被简单地忽略了,在模板中我只有一个“文本”类型的字段,而不是“日期”。 Dosbodoke 的回答效果很好。
  • 很高兴您得到了所需的帮助。为了将来参考,您应该直接提出问题以获得您需要的帮助。您的评论“我的问题是......”实际上仍然没有提出问题。

标签: python django


【解决方案1】:

在你的forms.py中你可以创建一个类

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

class Meta:
   model = Interview
   fields = ['topics', 'date_planned']
   widgets = {'date_planned': DateInput(),}

应该可以,除非是 DatePicker 问题。

【讨论】:

  • 谢谢。您的直截了当的回答提供了一个直接可行的解决方案。
【解决方案2】:

感谢 Dosbodoke,完整的答案应该如下所示:

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

class InterviewForm(ModelForm):
    class Meta:
        model = Interview
        fields = ['topics', 'date_planned']
        widgets = {'date_planned': DateInput(),}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-26
    • 2012-01-18
    • 2011-01-21
    • 2011-09-22
    • 1970-01-01
    • 1970-01-01
    • 2010-10-14
    相关资源
    最近更新 更多