【问题标题】:Django ValidationError date format exceptionDjango ValidationError 日期格式异常
【发布时间】:2015-11-04 12:02:30
【问题描述】:

您好,我检查了有关我的答案的所有问题,但没有找到解决方案。今天我更改了我的 CustomUser 模型,然后它停止工作。我想,当 django 询问我有关 datefield 的默认值并添加“”(空字符串)时,我失败了一件事,但我不确定。
我尝试删除所有 db 表并再次迁移,尝试删除所有迁移但仍然无法工作
我的模型:

  class UserManager(BaseUserManager):

    def create_user(self, username, email, password=None):
        if not email:
            raise ValueError('You must set email ')
        if not username:
            raise ValueError('User must have username')

        user = self.model( username=username, 
        email=self.normalize_email(email),
        )

        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_superuser(self, username, email, password):
        user = self.create_user(username=username, email=email, password=password)
        user.is_admin = True
        user.is_superuser = True
        user.save(using=self._db)
        return user

 class CustomUser(AbstractBaseUser, PermissionsMixin):

    alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', message='Only alphanumeric characters are allowed.')

    username = models.CharField(unique=True, max_length=30, validators= [alphanumeric])

    email = models.EmailField(
        'Email',
        max_length=255,
        unique=True,
        db_index=True
        )
    avatar = models.ImageField(
        'Avatar',
        blank=True,
        upload_to='user/avatar',
        default='user/default.jpg'
        )
    firstname = models.CharField(
        'First name',
        max_length=40,
        blank=True,
        )
    lastname = models.CharField(
        'Last name',
        max_length=40,
        blank=True,
        )
    date_of_birth = models.DateField(
        'Date of birth',
        null=True,
        blank=True,
        )
    register_date = models.DateField(
        'Register date',
        auto_now_add=True,
        null=True,
        blank=True,
        )
    is_active = models.BooleanField(
        'Active',
        default=True
        )
    is_admin = models.BooleanField(
        'Superuser',
        default=False
        )

    def age(self):
        x = date.today()
        if self.date_of_birth.year is None:
            return ''
        else:
            return x.year - self.date_of_birth.year     

    @property
    def is_staff(self):
        return self.is_admin

    def get_short_name(self):
        return self.email

    def __str__(self):
        return self.email

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, app_label):
        return True

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['username']

    objects = UserManager()

    class Meta:
        verbose_name = 'User'
        verbose_name_plural = 'Users'

我的服务器日志:
运行迁移:

 Rendering model states... DONE
  Applying admin.0001_initial... OK
  Applying sessions.0001_initial... OK
  Applying users.0008_auto_20151104_1042...Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/core/management/base.py", line 393, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/core/management/base.py", line 444, in execute
    output = self.handle(*args, **options)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 222, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 110, in migrate
    self.apply_migration(states[migration], migration, fake=fake, fake_initial=fake_initial)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/migrations/executor.py", line 148, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/migrations/migration.py", line 115, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/migrations/operations/fields.py", line 201, in database_forwards
    schema_editor.alter_field(from_model, from_field, to_field)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 484, in alter_field
    old_db_params, new_db_params, strict)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 567, in _alter_field
    new_default = self.effective_default(new_field)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 211, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 710, in get_db_prep_save
    prepared=False)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1322, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1317, in get_prep_value
    return self.to_python(value)
  File "/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/models/fields/__init__.py", line 1287, in to_python
    params={'value': value},
django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]

【问题讨论】:

    标签: python django django-models


    【解决方案1】:
    django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]
    

    正如错误消息所说,空字符串是日期的无效值。您可以提供所需格式的字符串,例如"2015-11-04",或使用 python 的date,例如date.today().

    但是,我有点担心您在迁移中会发生迁移0008 的这种变化。在现有项目中更改为自定义用户非常非常棘手(请参阅warning in the docs)。如果您删除所有用户迁移并重新创建它们,那么它应该从头开始创建模型,并且根本不需要默认日期。

    【讨论】:

    • 这是我的第一个学习项目,所以不要担心。我不明白我的模型在哪里需要更改默认日期格式。我删除了所有表,然后再次开始迁移,为什么我仍然有异常。
    • 确保在重新启动数据库时也删除迁移文件。
    • 它有效。我再次删除了数据库中的所有迁移和所有表。然后makemgrations每个应用程序。谢谢你的回答
    猜你喜欢
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-24
    • 1970-01-01
    • 2013-06-03
    相关资源
    最近更新 更多