[Django]-Django Templates – how do I output the relative path of file when using a FilePathField recursively

0πŸ‘

βœ…

I figured out that you can retrieve the path argument to the FilePathField using resource._meta.get_field(β€˜file_name’).path It seems best to do this in the model. So the model becomes:

RESOURCE_DIR = os.path.join(settings.MEDIA_ROOT, 'resources')

class Resource(models.Model):
    title = models.CharField(max_length=255)
    file_name = models.FilePathField(path=RESOURCE_DIR, recursive=True)

    def url(self):
        path = self._meta.get_field('file_name').path
        return self.file_name.replace(path, '', 1)

then in the template you can put:
{{ MEDIA_URL }}resources{{ resource.url }}

πŸ‘€gaumann

1πŸ‘

the below leaves in the leading path separator, which may not be the forward slash a url needs

def url(self):
    path = self._meta.get_field('file_name').path
    return self.file_name.replace(path, '', 1)

so slight improvement

def url(self):
        path = self._meta.get_field('icon').path
        return "/" + self.icon[len(path)+1:]
πŸ‘€user321393

0πŸ‘

this is kind of cheating:

{{ resource.file_name|cut:resource.file_name.path }}

not tested.

πŸ‘€Brandon Henry

Leave a comment