[“''%(value)s'的值格式无效。它必须采用YYYY-MM-DD HH:MM [:ss [.uuuuuu]] [TZ]格式。”]如果我检查full_clean,则会显示()

时间:2019-05-20 20:44:16

标签: django validation datetime pytz

尝试使用full_clean()查看对象是否有效时,出现以下错误。

django.core.exceptions.ValidationError: {'schedule_date': ["'%(value)s' value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]}

我尝试了这里推荐的所有格式,但是它们都不适合我

Whats the correct format for django dateTime?

创建Object.objects.create(...)之类的对象时不会出现错误

这是我的models.py

from datetime import datetime, timedelta, date
from django.db import models
from django import forms
from django.utils import timezone
from django.core.exceptions import ValidationError

from userstweetsmanager.constants import LANGUAGE_CHOICES

def password_validator(value):
    if len(value) < 6:
        raise ValidationError(
            str('is too short (minimum 6 characters)'),
            code='invalid'
        )

class User(models.Model):
    name = models.TextField(max_length=30, unique=True)
    password = models.TextField(validators=[password_validator])
    twitter_api_key = models.TextField(null=True, blank=True)
    twitter_api_secret_key = models.TextField(null=True, blank=True)
    twitter_access_token = models.TextField(null=True, blank=True)
    twitter_access_token_secret = models.TextField(null=True, blank=True)
    expire_date = models.DateField(default=date.today() + timedelta(days=14))
    language = models.TextField(choices=LANGUAGE_CHOICES, default='1')

def schedule_date_validator(value):
    if value < timezone.now() or timezone.now() + timedelta(days=14) < value:
        raise ValidationError(
            str('is not within the range (within 14 days from today)'),
            code='invalid'
        )

def content_validator(value):
    if len(value) > 140:
        raise ValidationError(
            str('is too long (maximum 140 characters)'),
            code='invalid'
        )

class Tweet(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    content = models.TextField(validators=[content_validator])
    schedule_date = models.DateTimeField(validators=[schedule_date_validator])

这是发生错误的测试代码:

    def test_valid_tweet(self):
        owner = User.objects.get(name="Hello")
        tweet = Tweet(user=owner, content="Hello world!", schedule_date=timezone.now())
        try:
            tweet.full_clean() # error occurs here
            pass
        except ValidationError as e:
            raise AssertionError("ValidationError should not been thrown")
        tweet.save()
        self.assertEqual(len(Tweet.objects.all()), 1)

当我测试了在python manage.py shell中创建对象时,它将导致错误,但是如果我执行full_clean(),则将导致错误。

1 个答案:

答案 0 :(得分:0)

问题在于代码的逻辑。我指定的时间范围不允许schedule_datetimezone.now()

的百万分之一秒

看了DateTimeField的源代码之后,似乎如果我有我的验证器抛出code =“ invalid”,它将仅显示以上错误消息,这使我感到困惑。代码是错误的。