Code

Opened 4 years ago

Closed 4 years ago

Last modified 4 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:

Description

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.

Attachments (0)

Change History (3)

comment:1 Changed 4 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/base.py 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 4 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 4 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 :)

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.