Regression: FileField calls validate during form validation; breaks auto_now_add date fields
|Reported by:||russellm||Owned by:||aaugustin|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
Unfortunately, this means that the filename function provided as an argument to upload_to can no longer reference any field with a pre-save behavior.
The common use case for this is to organize files on disk according to upload date. For example:
def user_filename(instance, filename): return os.path.join('user_files', instance.uploaded_timestamp.strftime('%Y-%m-%d'), filename) class UserFile(models.Model): uploaded_timestamp = models.DateTimeField(auto_now_add=True) data = models.FileField(upload_to=user_filename)
Under Django 1.5, attempting to call is_valid() on a Modelform for this model will raise a "'NoneType' object has no attribute 'strftime'" exception, because instance.uploaded_timestamp hasn't been instantiated yet. This is despite the fact that the uploaded data has been provided, the generated filename would be valid, and the upload timestamp can be computed.
In Django 1.4 and earlier, this works because no validation was performed for FileFields filenames; the uploaded_timestamp was evaluated as part of the model pre-save, and the persistence of the file to disk occurred after the model was saved.
To my reading, the documentation is ambiguous on whether this is expected behavior or not. It says that the model may not be saved to the database yet, but points at AutoField as the cause for problems. However, it also explicitly talks about using strftime as part of file paths. A file datetimes of 'now' would seem to be an obvious usage of this feature.
Change History (7)
comment:4 Changed 3 years ago by aaugustin
- Owner changed from nobody to aaugustin
- Status changed from new to assigned
comment:5 Changed 3 years ago by Aymeric Augustin <aymeric.augustin@…>
- Resolution set to fixed
- Status changed from assigned to closed