简体   繁体   中英

django file upload to dynamic path

I am trying to upload a file to django. So, I tried to use the code below to create a dynamic path for the file. But, it does not work.

I actually not sure how to use instance in model.py and how to pass path to def get_file_path. Specifically, What I want is that pass the file path from the function in views.py. For example, when I call something like docfile.save(filepath) , it will be saved in that filepath in django. Can you help me for this?

An example:

 docfile.save(path1)

it will be saved in /path1/file_name

Note: path1 could be anything and it is not related to any model field.

You could for example have an extra field (eg path ) on the model that specifies the path which you could then access via instance.path in get_file_path . You can't access arguments to save in this function.

You can write a custom file field.

class MyFieldField(FileField):

def get_path(self, attname):
        return 'path/to/%d' % self.id

def contribute_to_class(self, cls, name):
    super(MyFileField, self).contribute_to_class(cls, name)
    dispatcher.connect(self._post_init, signals.post_init, sender=cls)

def _post_init(self, instance=None):
    if hasattr(instance, 'get_path'):
        self.upload_to = instance.get_path(self.attname)

def db_type(self):
    return 'varchar(100)'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM