Home > Back-end >  How to make dynamic source path of FileFieldPath in django?
How to make dynamic source path of FileFieldPath in django?

Time:11-11

Info: I am try to use FileFieldPath in django. I want to make FileFieldPath(path=dynamic). I want to make every user have there own Directory path for file selection. Is there a way to user define his path from django Admin?

class SourcePath(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    source = models.CharField(max_length=255)


class Articles(models.Model):
    post_by = models.ForeignKey(User, on_delete=models.CASCADE)
    file_path = models.FilePathField(path=SourcePath.source)

CodePudding user response:

try to set the path value as callable function

def get_path(instance, filename):
    return "site_media/jobs/%s_%s/%s" % (instance.client, instance.job_number, filename)


class Articles(models.Model):
    ....
    file_path= models.FilePathField(path=get_path, match=".*\.pdf$", recursive=True)

but I'm not sure if this works, I didn't test it.

CodePudding user response:

You can add a path field and user can save the path to this field and your model can use this for path. Here's an Example :

class Articles(models.Model):
    post_by = models.ForeignKey(User, on_delete=models.CASCADE)
    path = models.CharField(max_length=255)
    file_path = models.FilePathField(path=self.path)
  • Related