Reputation: 21
This is for a game mod filesharing site. I have Apps Mods and Games. Each hold, you guessed it, Mods and Games!
Here is my Mods model:
from django.db import models
# Register storage backend TODO
def mod_directory_path(instance, filename):
# file will be uploaded to MEDIA_ROOT/<game>/<filename>
# Example code from https://docs.djangoproject.com/en/1.9/ref/models/fields/
return 'user_{0}/{1}'.format(instance.user.id, filename)
# Create your models here.
class Mods(models.Model):
title = models.CharField(max_length=30)
author = models.CharField(max_length=30)
game = models.ForeignKey(
'games.Games',
on_delete=models.CASCADE,
)
website = models.URLField()
repoWebsite = models.URLField()
upload = models.FileField(upload_to=mod_directory_path)
Here is my Games model:
from django.db import models
# Create your models here.
class Games(models.Model):
title = models.CharField(max_length=30)
developer = models.CharField(max_length=30)
website = models.URLField()
slug = models.SlugField()
I want to autoset the mod_directory_path to the slug of the Games model.
For example, if Mod item "Dynamic War Sandbox" has a ForeignKey of a unique ID pointing to the Arma 3 game, I want the file upload path to be based on the slug of the database entry for Arma 3.
MEDIA_ROOT/arma-3/<filename>.
How would I do this?
Upvotes: 2
Views: 374
Reputation: 13058
Something like this should work. The only requirement is that the game already exists in your database before the mod is being created.
def mod_directory_path(instance, filename):
slug = instance.game.slug
return os.sep.join([slug, filename])
Upvotes: 1