user514310
user514310

Reputation:

dynamic FileField path

I'm trying to use get_file_path function to generate dynamic path. Can I use Album slug field instead of this str(instance.id) in get_file_path? thanks

Here is models

def get_file_path(instance, filename):
    return os.path.join('files', str(instance.id), filename)

class Album(models.Model):
    name = models.CharField(max_length=100)
    slug = models.SlugField(unique = True,max_length=100,help_text="Suggested value automatically generated from name. Must be unique.")
    path = models.CharField(max_length=100,null=True, blank=True)
    language = models.ForeignKey(Category)
    albumid = models.CharField(max_length=100)

class Song(models.Model):
    title = models.CharField(max_length=100)
    artist = models.ManyToManyField(Artist)
    music = models.ForeignKey(Music)
    album = models.ForeignKey(Album)
    file = models.FileField(upload_to=get_file_path)

Update: I tried instance.slug . Its not working. instance.slug does not exist in Song Model. Its only exists in Album model ( Want to use Album Slug field) Update2: Here is model snapshot

Upvotes: 0

Views: 186

Answers (2)

DrTyrsa
DrTyrsa

Reputation: 31951

Quite straightforward: str(instance.album.slug)

Upvotes: 2

gecco
gecco

Reputation: 18830

Yes, just use instance.slug instead of instance.id

Another example you can find in the answer of post Change filename before save file in Django

Update: If not all instances have a slug field than you could be interested in a solution like this:

def get_file_path(instance, filename):
    fld = getattr(instance, 'slug', instance.id)
    return os.path.join('files', str(fld), filename)

Upvotes: 0

Related Questions