尝试为Django TimeField设置input_formats时发生错误

时间:2019-03-05 19:10:21

标签: django modelform timefield

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

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个小时,分别是am和pm。 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'

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

1 个答案:

答案 0 :(得分:1)

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