Leo505
Leo505

Reputation: 107

Django FileField upload_to assistance

I'm new to python and trying to adapt to the OOP of Python. Could someone explain why the following is saving in a folder called 'None'? I want to upload an audio file in the admin page. This file gets stored in its own folder with the 'Vocab name'

class Vocab(models.Model):
module = models.ForeignKey(Modules, on_delete=models.CASCADE)
number = models.CharField(max_length = 250)
name = models.CharField(max_length = 250)

class VocabContent(models.Model):
vocab = models.ForeignKey(Vocab, on_delete=models.CASCADE)
audio = models.FileField(upload_to=vocab.name)

Running the following on shell.

>>> from module.models import Modules, Vocab, VocabContent
>>> vocab = VocabContent.objects.get(pk=1)   
>>> vocab.vocab.name
'Numbers'

Numbers is the value i am looking for.

Upvotes: 0

Views: 1069

Answers (1)

Ícaro
Ícaro

Reputation: 1610

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.

Upvotes: 1

Related Questions