Opened 12 years ago

Closed 12 years ago

#19876 closed Bug (wontfix)

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

Reported by: Baptiste Mispelon 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).

Change History (1)

comment:1 by Carl Meyer, 12 years ago

Resolution: wontfix
Status: newclosed

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?

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