Opened 3 years ago

Closed 3 years ago

Last modified 3 years ago

#18607 closed Bug (invalid)

ModelForms do not recognize DateTimeFields with auto_now=True

Reported by: Adys Owned by: nobody
Component: Forms Version: 1.4
Severity: Normal Keywords:
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When creating a model with a DateTimeField(auto_now=True), the field is not present in a ModelForm (affects the django admin).

>>> from django.db.models import *
>>> from django.forms import ModelForm
>>> class Test(Model):
...  pub_date = DateTimeField(auto_now=True)
...  class Meta:
...   app_label = "editor"
... 
>>> class TestForm(ModelForm):
...  class Meta:                                                                                                                                                                                                                            
...   model = Test                                                                                                                                                                                                                          
... 
>>> TestForm()
<TestForm object at 0x2603890>
>>> TestForm().fields
{}

Removing auto_now lets the field be recognized. This is a regression since django 0.9 if that's worth anything.

Change History (3)

comment:1 Changed 3 years ago by akaariai

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to invalid
  • Status changed from new to closed

It seems this is intentional. The user is not supposed to edit the field, and thus it is not present in the form. It seems you can display the field with using readonly_fields. http://stackoverflow.com/questions/10033422/cant-display-datefield-on-form-with-auto-now-true

comment:2 Changed 3 years ago by Adys

In that case, it's something worth mentioning in the docs (either in the ModelForm or the DateTimeField or both), it was the source of a lot of pain and work trying to figure out what was going on, especially as it's a regression.

comment:3 Changed 3 years ago by akaariai

It kind of is: the auto_now documentation says that setting it to true implies editable=False, and editable is documented as:

If False, the field will not be editable in the admin or via forms automatically generated from the model class. Default is True.

Now, the editable documentation could perhaps be a little cleaner - it doesn't explicitly state the field is totally removed from the form, just that it is not editable.

As for regressions, I don't think there are any guarantees for pre 1.0 versions.

Note: See TracTickets for help on using tickets.
Back to Top