Django templates - how can I infer the relative path of a file when recursively using FilePathField

I have the following django model:

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) 

and I want to specify the URL of the file in the template so that the user can view or download it.

If I use {{ resource.file_name }} in the template, it displays the full path to the file on the server, for example. if RESOURCE_DIR='/home/foo/site_media/media' outputs '/home/foo/site_media/media/pdf/file1.pdf' , whereas I want 'pdf/file1.pdf' . In admin or modelform, the option is displayed as '/pdf/file1.pdf' in the selection element. Therefore, obviously, you can do what I ask. Of course, an additional slash is not important. If I set recursive=False , then I could just delete part of the path to the last slash.

How can I get the same result as modelform or admin?

+4
source share
3 answers

I realized that you can get the path argument in FilePathField using resource._meta.get_field ('filename'). The Way It seems best to do this in a model. Thus, 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}}

0
source

bottom leaves in the main path separator which cannot be the forward slash required by url

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

so little improvement

 def url(self): path = self._meta.get_field('icon').path return "/" + self.icon[len(path)+1:] 
+1
source

This is kind of a hoax:

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

not verified.

0
source

Source: https://habr.com/ru/post/1300949/


All Articles