gpt4 book ai didi

python - 使用 Django SelectDateWidget 设置默认日期

转载 作者:太空宇宙 更新时间:2023-11-03 16:16:05 26 4
gpt4 key购买 nike

首先,这个问题已经被问过here ,但是答案不起作用,并且也适用于 Django 1.3。在对 SO、Django Docs 和一般谷歌搜索上的类似问题进行了广泛的研究后,我仍然找不到有效的答案。这并不是一个重要的细节,但在尝试使用我正在创建的表单时以及因为我无法解决它时,它都很烦人。

在 ModelForm 中使用 SelectDateWidget 时,我希望能够将小部件上的默认值设置为今天的日期。

forms.py

from django import forms
from .models import Article
from django.utils import timezone

class ArticleForm(forms.ModelForm):
publish=forms.DateField(widget=forms.SelectDateWidget(), initial = timezone.now)
class Meta:
model = Article
fields = [
'title',

...

'publish',
]

models.py

from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone

from Blog.models import Category

class Article(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length = 120, unique=True)

...

publish = models.DateField(default=timezone.now)

我假设我在某个地方有一些语法错误,但我并没有找到它。

最佳答案

在设置 DateTimeFieldDateField 的默认时间时,看起来有细微的差别。

DateField.auto_now_add Automatically set the field to now when the object is first created. Useful for creation of timestamps. Note that the current date is always used; it’s not just a default value that you can override. So even if you set a value for this field when creating the object, it will be ignored. If you want to be able to modify this field, set the following instead of auto_now_add=True:

For DateField: default=date.today - from datetime.date.today() For DateTimeField: default=timezone.now - from django.utils.timezone.now()

因此,您需要使用 date.today 而不是 timezone.now

关于python - 使用 Django SelectDateWidget 设置默认日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38934402/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com