Return only the name of the file in the view

1

How do I display only the file name, example RET_PREF_ANAPOLIS ..., removing the path arquivos/ ?

models.py:

defuser_directory_path(instance,filename):ifinstance.tipo_arquivo.id==1:tipo='RET'elifinstance.tipo_arquivo.id==2:tipo='REM'filename='%s_%s_%s'%(tipo,instance.empresa.nome_empresa,filename)returnos.path.join('arquivos',filename)classDocumento(models.Model):arquivo=models.FileField(upload_to=user_directory_path)tipo_arquivo=models.ForeignKey('TipoArquivo',on_delete=models.CASCADE)empresa=models.ForeignKey('Empresa',on_delete=models.CASCADE)data_upload=models.DateTimeField(auto_now=True)def__str__(self):returnself.arquivo

views.py

classUploadArquivo(CreateView):model=Documentofields=['arquivo','tipo_arquivo','empresa']template_name='upload_arquivo.html'success_url=reverse_lazy('lista_empresa')classListaArquivo(ListView):model=Documentofields=['arquivo','tipo_arquivo','empresa']template_name='lista_arquivo.html'

viewupload_arquivo.html

<formmethod="post" enctype="multipart/form-data">{% csrf_token %}
    {{ form.as_p }}
    <input type="submit" value="Enviar">
</form>

view file_list.html

<h1>Arquivos</h1>
<table border="1">
    <thead>
        <th>Arquivo</th>
        <th>Tipo</th>
        <th>Empresa</th>
        <th>Download</th>
    </thead>
    <tbody>
        {% for documento in object_list %}
        <tr>
        <td>{{ documento.arquivo }}</td>
        <td>{{ documento.tipo_arquivo }}</td>
        <td>{{ documento.empresa }}</td>
        <td><a href="{{ documento.arquivo.url }}" download="">Download</a></td>
        </tr>
        {% endfor %}
    </tbody>
</table>
    
asked by anonymous 16.12.2018 / 22:30

1 answer

1

Use the basename function of the os.path module:

>>> from os import path
>>> a='/usr/local/share/pixmaps/sample_image.png'
>>>> path.basename(a)
'sample_image.png'

You can create a function within the model to return this value:

class Documento(models.Model):
# ...
@property
def apenas_o_nome_do_arquivo(self):
    return path.basename(self.arquivo)

And inside the template call it as:

<td>{{ documento.apenas_o_nome_do_arquivo }}</td>
    
17.12.2018 / 01:03