Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 2.7 unbound method with Django 1.7 migrations

I am upgrading to Django 1.7.4 and use the new built-in migrations, but I get the following error when attempting to run makemigrations:

ValueError: Could not find function upload_callback in app_utils.
Please note that due to Python 2 limitations, you cannot serialize unbound 
method functions (e.g. a method declared and used in the same class body). 
Please move the function into the main module body to use migrations.For more information, 
see https://docs.djangoproject.com/en/1.7/topics/migrations/#serializing-values

My model definition:

class Discount(models.Model):
    banner = models.ImageField(
        help_text=_("Banner image for this discount"),
        upload_to=upload_to('discounts/', 'title'),
        blank=True,
        null=True
    )

And my upload callback in app_utils.py:

def upload_to(path, attribute=None):
    def upload_callback(instance, filename):
        compact = filename[:50]
        try:
            attr= unicode( slugify( getattr(instance, attribute) ) )
            mypath = '%s/%s/%s' % (path, attr, compact)
        except:
            mypath = '%s%s' % (path, compact)
        return mypath
    return upload_callback

Based on the error message, it indicates upload_callback is unbound. So I tried pulling upload_callback outside of the the wrapper function, but cannot find a way to pass in the extra path and attribute parameters passed into upload_to. Django's documentation is unclear how to do this, and it only specifies that instance and filename are required.

Ideally, what I would like is:

def upload_to(instance, filename, path, attribute=None):
    ...

Any ideas how I can go about achieving this?

like image 670
Chris Avatar asked Mar 15 '23 12:03

Chris


1 Answers

After some serious deep digging on the web, I came across this Django bug report. The solution seems to create a callable factory class:

https://code.djangoproject.com/ticket/22999

More discussion here: Django - Cannot create migrations for ImageField with dynamic upload_to value

like image 197
Chris Avatar answered Mar 25 '23 05:03

Chris