在Django中将CreateView字段显示为DateTimePicker

如何将此“ date_delivery”字段显示为DateTimePicker?现在,它会自动生成为'input type =“ text”'

在models.py中

class MyMachine(models.Model):
    date_delivery = models.DateTimeField(null=True, verbose_name='Datum Dostave:')
    machine_name = models.ForeignKey(MyName, on_delete=models.PROTECT)
    machine_model = models.ForeignKey(MyModel, on_delete=models.PROTECT)
    machine_serial = models.CharField(max_length=15)
    language = models.ForeignKey(MyLanguage, on_delete=models.PROTECT)

在views.py中

class MyMachineCreateView(CreateView):
    model = MyMachine
    fields = ['date_delivery', 'machine_name', 'machine_model', 'machine_serial', 'language', ]

在Django Admin中显示良好

enter image description here

但是以html形式不

enter image description here

评论
万伶伶
万伶伶

这是表格的好用法。该表单用于添加视图创建的基本表单中未提供的自定义功能:

from django import forms
from datetime import date

class MachineForm(forms.ModelForm):
    class Meta():
        model = MyMachine
        fields = ('date_delivery', 'machine_name', 'machine_model', 'machine_serial', 'language')
        widgets = {
             'date_delivery': forms.DateInput(
                    format='%Y-%m-%d',
                    attrs={'value': date.today(), 'type': 'date'})
         }

The widgets command adds the date widget to the date_delivery field. You can feel free to change format and the value argument in attrs supplies the default value. You can omit this or change it to some other date.

然后在您的视图中导入表单并将字段行替换为:

form_class = MachineForm
点赞
评论