mgs
mgs

Reputation: 2689

django dynamic FilePathField

class Project(models.Model):
    slug = models.SlugField(max_length=100)
    main_file = models.FilePathField(path="/home/mn/myfiles/%s" % slug)

This code doesn't work, just illustrating what I'd like to do. I want to fill in FilePathField when object is accessed (ie. when it is updated in django admin, not when it's created).

Is there a hook where you can set fields just before they are filled? Something like object.on_get(instance): ... perhaps?

Upvotes: 0

Views: 1649

Answers (1)

c_harm
c_harm

Reputation:

It's unclear what your intentions here are.

Since Model instances are just Python classes, you can do this by a method on the Project class:

class Project(models.Model):
    slug = models.SlugField(max_length=100)

    @property
    def main_file(self):
         return "/home/mn/myfiles/%s" % self.slug

If you want to manually specify a location outside of MEDIA_ROOT to upload files to, you will need to subclass django.db.models.fields.files.FileField and overwrite the __init__ method.

Upvotes: 1

Related Questions