2

I've been getting the following error when trying to use migrations over a model that has a FileField with a dynamic upload_to path.

    field=models.FileField(null=True, upload_to=core.models.UserProfile.upload_path, blank=True),
AttributeError: type object 'UserProfile' has no attribute 'upload_path'

My code:

def upload_path(instance, filename):
    return os.path.join(str(instance.user.id),filename)

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')
    document_upload = models.FileField(upload_to=upload_path,null=True, blank=True)
ip.
  • 3,306
  • 6
  • 32
  • 42
  • Delete the migration file and run `makemigrations` again. – Leistungsabfall Jun 03 '15 at 15:27
  • Since the `upload_path()` function is not inside a class, it shouldn't have the first argument `self` but rather look like `def upload_path(instance, filename)`. Did you previously try to have it inside the class? The error message also suggests to search for it there rather than in `core.models.upload_path`. – sthzg Jun 03 '15 at 17:35
  • @Leistungsabfall that didn't work. – ip. Jun 03 '15 at 17:37
  • @sthzg yes its a mistake from a previous try but that's not the problem – ip. Jun 03 '15 at 17:37
  • Thought so. Did the exception stay exactly the same after you've pulled `update_path` outside to the module? Because from what it prints it searches for the `upload_path` callable inside `UserProfile`. – sthzg Jun 03 '15 at 17:47

1 Answers1

1

You can use the @deconstructor class decorator, this allows the decorated class to be serialized by the migrations subsystem

Example

from django.utils.deconstruct import deconstructible

@deconstructible
class UploadPath(object):

    def __call__(self, instance, filename):
        return os.path.join(str(instance.user.id),filename)

upload_path= UploadPath()

class UserProfile(models.Model):
    user = models.OneToOneField(User, related_name='userprofile')
    document_upload = models.FileField(upload_to=upload_path, null=True, blank=True)

Read more:

Community
  • 1
  • 1
Jopr
  • 310
  • 3
  • 8
  • It's an old question but I stumbled upon it and thought it might be useful for others to have it answered :) – Jopr Mar 18 '16 at 08:31