在django Form中将字段初始化为常量值
Initialize field to constant value in django Form
如何设置model/form组合,使模型中的字段初始化为固定值,在向用户呈现表单时不显示表单元素?
我只想在每次从表单创建新的 Source
时初始化 Source.updated = datetime.datetime(2000, 1, 1, 0, 0, 0, 0)
。用户无法覆盖此初始默认设置。 (后续与app交互会导致这个字段值发生变化,但不只是auto_now
因为我希望初始值远在过去。)
我现在拥有的是
class Source(Model):
name = models.CharField(max_length=168, help_text="Source name")
link = models.URLField(primary_key=True, help_text="Data source link")
type = models.CharField(max_length=64, help_text="Data source type")
# TODO: add this field to the model.
# have it initialize to 2000-01-01
#updated = models.DateTimeField(help_text="Most recent time this source has been updated")
class SourcesForm(forms.ModelForm):
class Meta:
model = models.Source
fields = ['name', 'link', 'type',]
# TBD: how to configure the form so that
# it initializes the "updated" field with a fixed value
# when .save() is called
我试图实现的逻辑是:我们正在从远程源获取数据,所以我想知道最近更新此数据的时间是什么时候。
您可以设置 editable=False
[Django-doc] 以防止该字段在 ModelForm
、ModelAdmin
等时间出现:
from datetime import datetime
class Source(Model):
# …
updated = models.DateTimeField(<strong>editable=False, default=datetime(2000, 1, 1)</strong>, help_text="Most recent time this source has been updated")
如何设置model/form组合,使模型中的字段初始化为固定值,在向用户呈现表单时不显示表单元素?
我只想在每次从表单创建新的 Source
时初始化 Source.updated = datetime.datetime(2000, 1, 1, 0, 0, 0, 0)
。用户无法覆盖此初始默认设置。 (后续与app交互会导致这个字段值发生变化,但不只是auto_now
因为我希望初始值远在过去。)
我现在拥有的是
class Source(Model):
name = models.CharField(max_length=168, help_text="Source name")
link = models.URLField(primary_key=True, help_text="Data source link")
type = models.CharField(max_length=64, help_text="Data source type")
# TODO: add this field to the model.
# have it initialize to 2000-01-01
#updated = models.DateTimeField(help_text="Most recent time this source has been updated")
class SourcesForm(forms.ModelForm):
class Meta:
model = models.Source
fields = ['name', 'link', 'type',]
# TBD: how to configure the form so that
# it initializes the "updated" field with a fixed value
# when .save() is called
我试图实现的逻辑是:我们正在从远程源获取数据,所以我想知道最近更新此数据的时间是什么时候。
您可以设置 editable=False
[Django-doc] 以防止该字段在 ModelForm
、ModelAdmin
等时间出现:
from datetime import datetime
class Source(Model):
# …
updated = models.DateTimeField(<strong>editable=False, default=datetime(2000, 1, 1)</strong>, help_text="Most recent time this source has been updated")