0

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.

Leo505
  • 109
  • 1
  • 13

1 Answers1

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.

Community
  • 1
  • 1
Ícaro
  • 1,432
  • 3
  • 18
  • 36
  • Worked like a charm... Just a questions for my Python learning. Any reason why the function is outside the class and not within it? – Leo505 Oct 24 '16 at 18:21
  • @Leo505 AFAIK it doesn't make a difference, but you'd need to add a `@classmethod` annotation to the function if you move it inside the model and reference it as `VocabContent. get_upload_path` in your field. – Ícaro Oct 24 '16 at 19:41