Django ValidationError日期格式异常 [英] Django ValidationError date format exception
问题描述
我试图删除所有的db表并再次迁移,尝试删除所有迁移,仍然不工作
我的模型:
class UserManager(BaseUserManager):
def create_user(self,username,email,password = None)
如果不是电子邮件:
raise ValueError('你必须设置电子邮件')
如果没有用户名:
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)
返回用户
def create_superuser(self,username ,电子邮件,密码):
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 ='只允许使用字母数字字符')
username = models.CharField(unique = True,max_length = 30,validators = [alphanumeric])
email = models.EmailField(
'Email',
max_length = 255,
unique =
db_index = True
)
avatar = models.ImageField(
'头像',
blank = True,
upload_to ='user / avatar'
default ='user / default.jpg'
)
firstname = models.CharField(
'名字',
max_length = 40,
blank = true,
)
lastname = models.CharField(
'姓氏',
max_length = 40,
blank =真的,
)
date_of_birth = models.DateField(
'出生日期',
null = True,
blank = True,
)
register_date = models.DateField(
'注册日期',
auto_now_add = True,
null = True,
blank = True,
)
is_active = models.BooleanField(
'Active',
default = True
)
is_admin = models.BooleanField(
'Superuser',
default =假
)
定义年龄(自):
x = date.today()
如果self.date_of_birth.year是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.em ail
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'
我的服务器日志: >
运行迁移:
呈现模型状态... DONE
应用admin.0001_initial ... OK
应用sessions.0001_initial ... OK
应用users.0008_auto_20151104_1042 ...追溯(最近的最后一次呼叫):
文件manage.py,第10行在< module> ;
execute_from_command_line(sys.argv)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/core/management/__init__.py,第338行, execute_from_command_line
utility.execute()
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/core/management/__init__.py,第330行,执行
self.fetch_command(子命令).run_from_argv(self.argv)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/core/management/base .py,行393,在run_from_argv
self.execute(* args,** cmd_options)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django /core/management/base.py,第444行,执行
output = self.handle(* args,** options)
文件/ home / ivan / diabetes_django / venv / lib / python3 .4 / site-packages / django / core / management / commands / migrate.py,第222行,处理
executor.migrate(targets,plan,fake = fake,fake_initial = fake_initial)
文件/ home / ivan / diabetes_django / venv / lib / python3.4 / site-packages / django / db / migrations / executor.py,第110行,迁移
self.apply_migration(状态[迁移],迁移,假= fake,fake_initial = fake_initial)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/migrations/executor.py,第148行在apply_migration $ b中$ b state = migration.apply(state,schema_editor)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/migrations/migration.py,第115行,在应用
operation.database_forwards(self.app_label,schema_editor,old_state,project_state)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/迁移/操作/ fields.py,第201行,database_forwards
schema_editor.alter_field(from_model,from_field,to_field)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site -packages / django / db / backends / base / schema.py,第484行,在alter_field
old_db_params ,new_db_params,strict)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py,第567行,在_alter_field
new_default = self.effective_default(new_field)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/backends/base/schema.py,第211行,in effective_default
default = field.get_db_prep_save(default,self.connection)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/models/字段/ __ init__.py,第710行,在get_db_prep_save
prepared = False)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/django/db/models /fields/__init__.py,第1322行,get_db_prep_value
value = self.get_prep_value(value)
文件/home/ivan/diabetes_django/venv/lib/python3.4/site-packages/ django / db / models / fields / __ init__.py,第1317行,get_prep_value
return self.to_python(value)
文件/ home / ivan / diabetes_django / venv /lib/python3.4/site-packages/django/db/models/fields/__init__.py,第1287行,to_python
params = {'value':value},
django.core .exceptions.ValidationError:['值的日期格式无效。它必须是YYYY-MM-DD格式。]
pre> django.core.exceptions.ValidationError:[''值的日期格式无效。它必须是YYYY-MM-DD格式。]
正如错误消息所示,空字符串是日期的无效值,您可以提供所需格式的字符串,例如2015-11-04
,或使用python的日期
,例如 date.today()
。
然而,稍微担心您的迁移中有这种迁移变更 0008
。在现有项目中更改为自定义用户非常棘手(请参阅<在文档中的href =https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#substituting-a-custom-user-model =nofollow>警告)如果您删除所有的用户迁移并重新创建它们,那么它应该从头开始创建模型,而不要求默认日期。
Hi I check all question about my answer and doesn't find solution. Today I change my CustomUser model and then it stop works. I think, I failed one thing, when django ask me about default value to datefield and I add "" (empty string), but I not sure.
I tried to delete all db tables and migrate again, tried delete all migrations and still don't work
My model:
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'
my server log:
Running migrations:
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."]
django.core.exceptions.ValidationError: ["'' value has an invalid date format. It must be in YYYY-MM-DD format."]
As the error message says, the empty string is an invalid value for a date. You could either provide a string in the required format, e.g. "2015-11-04"
, or use python's date
, e.g. date.today()
.
However, I'm slightly worried that you have this change in migration 0008
in your migrations. Changing to a custom user in an existing project is extremely tricky (see the warning in the docs). If you delete all your user migrations and recreate them, then it should create the model from scratch, and not ask for a default date at all.
这篇关于Django ValidationError日期格式异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!