[Fixed]-Django FileField upload_to assistance

1👍

It’s probably because the way you reference vocab.name is not defined when your model migration is run. I can’t explain precisely why this happens but a solution would be to use a callable as your upload_to to evaluate it at runtime and get the value correctly, much like this other answer: Dynamic File Path in Django

So, for you, you could have something like:

import os
def get_upload_path(instance, filename):
    return os.path.join("%s" % instance.vocab.name, filename)


class VocabContent(models.Model):
    vocab = models.ForeignKey(Vocab, on_delete=models.CASCADE)
    audio = models.FileField(upload_to=get_upload_path)  # Important to NOT put the parenthesis after the function name

Which would result in a path that concatenates the vocab.name to your file name for every new file.

👤Ícaro

Leave a comment