Initialize field to constant value in django Form
How can I set up a model/form combination so that the field in the model is initialized to a fixed value and there is no form element displayed when the form is presented to the user?
I just want to initialize Source.updated = datetime.datetime(2000, 1, 1, 0, 0, 0, 0)
each time a new Source
is created from a form. The user cannot over-ride this initial default. (Subsequent interaction with the app will cause this field value to change, but it's not just auto_now
because I want the initial value to be far in the past.)
What I have now is
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
The logic I'm trying to implement is that: we're getting data from a remote source, so I want to know when the most-recent time this data have been updated is.
You can set editable=False
[Django-doc] to prevent the field to show up in ModelForm
s, ModelAdmin
, etc.:
from datetime import datetime
class Source(Model):
# …
updated = models.DateTimeField(editable=False, default=datetime(2000, 1, 1), help_text="Most recent time this source has been updated")