Search code examples
pythondjangodjango-modelsdjango-file-upload

Django: Saving file to specific location


I am trying to find a way to save a file on a specific location each time its uploaded. Here are the models that I am working with.

class App(models.Model):
    name = models.CharField(max_length=20)
    description = models.CharField(max_length=20)

     def save(self, *args, **kwargs):
         new_media_root = os.path.join(settings.MEDIA_ROOT, self.name)
         os.mkdir(new_media_root)
     super(App, self).save(self, *args, **kwargs)

class Page(models.Model):
    title = models.CharField(max_length=20)
    app = models.ForeignKey(App)
    file = model.FileField(upload_to=app.name)

From the above code snippet, what i am trying to achieve is for every app created, the child pages save the files in a location of the App. Was calling the app name using upload_to=app.name but on saving, the file created is called 'None'. How would i got about solving this.


Solution

  • If upload_to is callable, the overwrite the generate_filename function.

    def generate_filename(self, instance, filename):
        directory_name = os.path.normpath(force_unicode(datetime.datetime.now().strftime(smart_str(self.app.name))))
        return os.path.join(directory_name, self.get_filename(filename))
    
    class Page(models.Model):
        title = models.CharField(max_length=20)
        app = models.ForeignKey(App)
        file = model.FileField(upload_to=generate_filename)