Django: Display File Name for Uploaded File

爷,独闯天下 提交于 2021-02-10 14:26:49

问题


In my model, I have a defined a FileField which my template displays it as a link. My problem is that the linked file displays the url as the name. What shows on html page is:

Uploaded File: ./picture.jpg

I've looked on the DjangoDocs regarding file names and a previous S.O. question, but just can't figure it out.

How can I:

  1. Have it display a different name, not a url.
  2. Allow the admin who uploaded the file to give it a name, which would then be viewed on the template.

my models.py:

class model_name(models.Model):
    attachment = models.FileField()

my views.py (if entry exists, display it, if not, return message):

from django.core.files import File
from vendor_db.models import model_name

def webpage(request, id):
    try:
        variable = model_name.objects.get(id=id)
    except model_name.DoesNotExist:
        raise Http404('This item does not exist')
    return render(request, 'page.html', {
        'variable': variable,
    })

my page.html:

<p>Uploaded File: <a href="{{ variable.attachment.url }}">{{ variable.attachment }}</a></p>

回答1:


For your code:

class model_name(models.Model):
    attachment = models.FileField()

attachment is a FileField object, that has a property called filename, so just ask for that property. i.e.

foo = model_name.objects.create(attachment=some_file)
foo.attachment.filename # filename as a string is returned



回答2:


In page.html:

<p>Uploaded File: <a href="{{ model.Attachment.url }}">{{ model.Attachment }}</a></p>

should be changed to:

<p>Uploaded File: {{ variable }}</p>



回答3:


To solve, I simply added an additional field to the models.py. This allows user to give it a name. and when displaying it on a page, call the Attachment and Attachment_Name as shown below. Hope this helps. No URL mess.

class model_name(models.Model):
    Attachment = models.FileField()
    Attachment_Name = models.CharField()

and in my html file:

<p>Uploaded File: <a href="{{ variable.Attachment.url }}">{{variable.Attachment_Name }}</a></p>


来源:https://stackoverflow.com/questions/36205155/django-display-file-name-for-uploaded-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!