Opened 5 years ago

Closed 5 years ago

Last modified 5 years ago

#13784 closed (duplicate)

pre_save is dispatched before executing upload_to attributes on FileFields when using ModelForm

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


Suppose you have this code:

def callable_upload_to(instance, filename):
    full_path = os.path.join(this_year(), filename)
    print "PLACING", full_path
    return full_path

class Foo(models.Model):
    file = models.FileField(upload_to=callable_upload_to)
    size = models.IntegerField(null=True)

def update_foo(sender, instance, **kwargs):
    print "UPDATING", str(instance.file)

pre_save.connect(update_foo, sender=Foo)

Suppose you create one of these instances with a ModelForm you'll get this output on stdout:

UPDATING sample.file
PLACING 2010/sample.file

That means that you can't rely on the file path as dictated by the upload_to callable in your pre_save signal. Especially important is that within your pre_save method you can't even get to the file since it doesn't exist.

Change History (3)

comment:1 Changed 5 years ago by peterbe

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

I suspect that the culprit is Model.save_base in django/db/models/ where it dispatches the signal before it does whatever it does to those meta.local_files but I don't understand the code enough to attempt a patch at this point.

comment:2 Changed 5 years ago by kmtracey

  • Resolution set to duplicate
  • Status changed from new to closed

This behavior got a fair amount of discussion when it was introduced. See #10788 and the linked threads on django-developers.

comment:3 Changed 5 years ago by peterbe

Oh I see. I really did google the tickets but didn't find that one.

Personally thinks it sucks but will keep my mouth shut till I provide a patch of my own :)

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