Opened 5 years ago

Closed 5 years ago

Last modified 14 months ago

#18607 closed Bug (invalid)

ModelForms do not recognize DateTimeFields with auto_now=True

Reported by: Jerome Leclanche 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


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 (4)

comment:1 Changed 5 years ago by Anssi Kääriäinen

Resolution: invalid
Status: newclosed

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.

comment:2 Changed 5 years ago by Jerome Leclanche

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 5 years ago by Anssi Kääriäinen

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.

comment:4 Changed 14 months ago by Ryan C. Schwiebert

The datetime field I'm using has editable=True and the ModelForm fails with the same problem. For insurance I also put auto_add=False and auto_now_add = False. Same problem.

Maybe the above comments explain the problem, but it doesn't explain how to overcome it.

Last edited 14 months ago by Ryan C. Schwiebert (previous) (diff)
Note: See TracTickets for help on using tickets.
Back to Top