alidationError at ["#x201c;< class' datetime.timezone'>”值具有无效格式。它必须以yyyy-mm-dd HH:mm [:ss [.uuuuuu]] [tz]格式。

发布于 2025-02-12 05:19:09 字数 6923 浏览 0 评论 0原文

我很难创建一种表格,以节省用户提交的时间。我收到以下错误:

django.core.exceptions.ValidationError: ["“<class 'datetime.timezone'>” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]```

model.py

class Post(models.Model):
    post = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    likes = models.IntegerField(default=0)
    date_and_time = models.DateTimeField(default=datetime.datetime.now, blank=True, null=True)

views.py

def index(request):
    if request.method == "POST":
        post_form = PostForm(request.POST)
        if post_form.is_valid():
            post = post_form.save(commit=False)
            post.user = request.user
            post.date_and_time = str(datetime.timezone)
            post.save()
        else: 
            return render(request, "network/index.html",{
                "form": post
            })
    post_form = PostForm
    return render(request, "network/index.html",{
        "form": post_form
    })

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['post']
        widgets = {'post': forms.TextInput(attrs={'placeholder': 'Create a new post here.'})
        }

我想通过post.date_and_time获得当前日期,但不确定如何处理。我使用dateTime.timezone在堆栈溢出上看到了其他一些帖子,因此我尝试了它,但是如果有更好的方法来实现此目的。

期间发生的错误

File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1388, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

python manage.py迁移整个错误消息


WARNINGS:
network.Post: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
        HINT: Configure the DEFAULT_AUTO_FIELD setting or the NetworkConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
network.User: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
        HINT: Configure the DEFAULT_AUTO_FIELD setting or the NetworkConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, network, sessions
Running migrations:
  Applying network.0003_post_date_and_time...Traceback (most recent call last):
  File "C:\Users\User Name\Downloads\network\project4\manage.py", line 21, in <module>
    main()
  File "C:\Users\User Name\Downloads\network\project4\manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
    schema_editor.add_field(
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field
    self._remake_table(model, create_field=field)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table
    self.effective_default(create_field)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 324, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1427, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1406, in get_prep_value
    value = super().get_prep_value(value)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1266, in get_prep_value
    return self.to_python(value)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1388, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

I am having trouble creating a form that saves the time that the user submits. I am receiving the following error:

django.core.exceptions.ValidationError: ["“<class 'datetime.timezone'>” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format."]```

models.py

class Post(models.Model):
    post = models.TextField()
    user = models.ForeignKey(User, on_delete=models.CASCADE, default="")
    likes = models.IntegerField(default=0)
    date_and_time = models.DateTimeField(default=datetime.datetime.now, blank=True, null=True)

views.py

def index(request):
    if request.method == "POST":
        post_form = PostForm(request.POST)
        if post_form.is_valid():
            post = post_form.save(commit=False)
            post.user = request.user
            post.date_and_time = str(datetime.timezone)
            post.save()
        else: 
            return render(request, "network/index.html",{
                "form": post
            })
    post_form = PostForm
    return render(request, "network/index.html",{
        "form": post_form
    })

forms.py

class PostForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = ['post']
        widgets = {'post': forms.TextInput(attrs={'placeholder': 'Create a new post here.'})
        }

I want to get the current date through post.date_and_time but am not sure how do to that. I saw some other posts on Stack Overflow using datetime.timezone, so I tried it but will change it if there is a better way to achieve this.

error that occurs during python manage.py migrate

File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1388, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

entire error message


WARNINGS:
network.Post: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
        HINT: Configure the DEFAULT_AUTO_FIELD setting or the NetworkConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
network.User: (models.W042) Auto-created primary key used when not defining a primary key type, by default 'django.db.models.AutoField'.
        HINT: Configure the DEFAULT_AUTO_FIELD setting or the NetworkConfig.default_auto_field attribute to point to a subclass of AutoField, e.g. 'django.db.models.BigAutoField'.
Operations to perform:
  Apply all migrations: admin, auth, contenttypes, network, sessions
Running migrations:
  Applying network.0003_post_date_and_time...Traceback (most recent call last):
  File "C:\Users\User Name\Downloads\network\project4\manage.py", line 21, in <module>
    main()
  File "C:\Users\User Name\Downloads\network\project4\manage.py", line 17, in main
    execute_from_command_line(sys.argv)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line
    utility.execute()
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv
    self.execute(*args, **cmd_options)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute
    output = self.handle(*args, **options)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 89, in wrapped
    res = handle_func(*args, **kwargs)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle
    post_migrate_state = executor.migrate(
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration
    state = migration.apply(state, schema_editor)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\migration.py", line 126, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards
    schema_editor.add_field(
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field
    self._remake_table(model, create_field=field)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table
    self.effective_default(create_field)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\backends\base\schema.py", line 324, in effective_default
    return field.get_db_prep_save(self._effective_default(field), self.connection)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 842, in get_db_prep_save
    return self.get_db_prep_value(value, connection=connection, prepared=False)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1427, in get_db_prep_value
    value = self.get_prep_value(value)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1406, in get_prep_value
    value = super().get_prep_value(value)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1266, in get_prep_value
    return self.to_python(value)
  File "C:\Users\User Name\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\fields\__init__.py", line 1388, in to_python
    raise exceptions.ValidationError(
django.core.exceptions.ValidationError: ['“” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

半步萧音过轻尘 2025-02-19 05:19:09

我认为您需要更改这里的只是post.date_and_time = timezone.now()(其中timezone来自来自django.utils import timzone

定义更改为:

date_and_time = models.DateTimeField(auto_now_add=True)

另一个选择是将您的模型 href =“ https://docs.djangoproject.com/en/4.0/ref/ref/models/fields/#django.db.models.datefield.auto_now_add” >文档对于auto_now_add之间的差异(仅在第一个创建时)和auto_now(每个更新上的更改)。

I think all you need to change here is post.date_and_time = timezone.now() (where timezone comes from from django.utils import timezone.

Another option would be to change your model definition to something like:

date_and_time = models.DateTimeField(auto_now_add=True)

see the models.DateTimeField docs for the difference between auto_now_add (only on first creation) and auto_now (changes on each update).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文