Code

#19876 closed Bug (wontfix)

Using a staticmethod for a FileField's upload_to attribute doesn't work

Reported by: bmispelon Owned by: nobody
Component: Database layer (models, ORM) Version: 1.5-rc-1
Severity: Normal Keywords: filefield upload_to staticmethod
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 trying to use a staticmethod for a FileField's upload_to attribute, the results are not what you'd expect.

# models.py

class Foo(models.Model):
    @staticmethod
    def my_callable(instance, filename):
        return 'foo'
    
    f = models.FileField(upload_to=my_callable)

The following code shows what happens:

from myapp.models import Foo

instance = Foo()
print instance._meta.get_field('f').generate_filename(instance, 'bar')

I would expect the output of this to be 'foo' but instead, it prints u'<staticmethod object at 0x1c8b130>/bar'.

Putting a breakpoint inside FileField.__init__, it appears that at the time the field is initialized, upload_to is a staticmethod object which is not itself callable (it has a __func__ attribute which is the callable we are looking for).

Attachments (0)

Change History (1)

comment:1 Changed 14 months ago by carljm

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

I don't think there's anything Django can do about this, it's just how staticmethods (and class bodies) work in Python. There's rarely a good reason for using a staticmethod in Python anyway, and the given example certainly isn't: a function within a class that takes an instance of that class is just a regular method, so why not make it one?

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.