0

I'm trying to use the reverse relation of a OneToOneField to build the path in an upload_to method of a FileField, like this:

def get_upload_path(asset, filename):
    # Using the reverse relation `game` here
    return '/'.join([asset.game.slug, filename])


class Asset(models.Model)
    file = models.FileField(upload_to=get_upload_path)


class Game(models.Model):
    slug = models.SlugField()
    menu_image = models.OneToOneField(Asset, related_name='game', null=True, blank=True)

I can create a Game with an empty asset no problem. When I change the game in the admin, and I add a new Asset to the menu image via the green + button, I get a RelatedObjectDoesNotExist error saying "Asset has no game" inside the popup. Is there a way to accomplish this? I've found some other answers saying it is, like here and here, but it's not working for me on Django 1.9.4.

Community
  • 1
  • 1
Justin Poliey
  • 16,289
  • 7
  • 37
  • 48

1 Answers1

1

the problem is in your 'get_upload_path' function, cause you're calling to asset.game.slug... but you don't have defined any game yet...

German Alzate
  • 801
  • 10
  • 19
  • I'm on the "Change game" page in the admin, after creating a game. I'm using the little green + button to add the asset. Does the popup not associate the game with the unsaved Asset instance? – Justin Poliey Jun 30 '16 at 21:09
  • you must especify what to do when you're saving a game... and then save a Asset... if you delete the upload_to function, i believe you dont have problems – German Alzate Jun 30 '16 at 21:20
  • Right, I know that's where the problem is coming from, I'm trying to figure out if there is a way to achieve what I'm trying to inside of the Django admin. – Justin Poliey Jun 30 '16 at 22:08