尝试为 Django TimeField 设置 input_formats 时出错

Getting an error when trying to set input_formats for Django TimeField

我正在使用以下模型来表示 Class:

class Class(models.Model):
  course = models.ForeignKey(Course, on_delete=models.CASCADE)
  day = models.CharField(max_length=10, choices=WEEK_DAYS)
  timing = models.TimeField(input_formats = ['%I:%M %p', ])
  room = models.CharField(max_length=10)

我想将 TimeField 的格式设置为 12 小时,包括上午和下午。 Django 的文档提到使用 input_formats 参数来完成此 here。但是,当我 运行 makemigrations 时,出现以下错误:

Traceback (most recent call last):
  File ".\manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "D:\Applications\Python\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line
    utility.execute()
  File "D:\Applications\Python\lib\site-packages\django\core\management\__init__.py", line 347, in execute
    django.setup()
  File "D:\Applications\Python\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "D:\Applications\Python\lib\site-packages\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "D:\Applications\Python\lib\site-packages\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "D:\Applications\Python\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\plannerly\timetable\models.py", line 15, in <module>
    class Class(models.Model):
  File "D:\plannerly\timetable\models.py", line 18, in Class
    timing = models.TimeField(input_formats = ['%I:%M %p', ])
  File "D:\Applications\Python\lib\site-packages\django\db\models\fields\__init__.py", line 2146, in __init__
    super().__init__(verbose_name, name, **kwargs)
TypeError: __init__() got an unexpected keyword argument 'input_formats'

我不太确定是什么原因造成的。有什么想法吗?

input_formats 用于 forms.DateField()[1]。 不是 model.DateField()[2] 选项。

您必须在您的表单中设置 input_fomats=[],而不是在您的模型中。

[1] https://docs.djangoproject.com/en/2.2/ref/forms/fields/#timefield

[2] https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.DateField