Django:显示上传文件的文件名 [英] Django: Display File Name for Uploaded File
问题描述
在我的模型中,我定义了一个 FileField
,我的模板将其显示为链接.我的问题是链接的文件将URL显示为名称.在html页面上显示的是:
上传的文件:./picture.jpg
我查看了 DjangoDocs 关于文件名的信息和以前的SO问题,但无法弄清楚./p>
我如何:
- 让它显示不同的名称,而不是URL.
- 允许上传文件的管理员给它起一个名字,然后可以在模板上查看它.
我的models.py:
class model_name(models.Model):附件= models.FileField()
我的views.py(如果存在条目,则显示它,如果不存在,则返回消息):
django.core.files中的 导入文件从vendor_db.models导入model_namedef网页(请求,ID):尝试:变量= model_name.objects.get(id = id)除了model_name.DoesNotExist:引发Http404('该项目不存在')返回render(request,'page.html',{'variable':变量,})
我的page.html:
< p>上传的文件:< a href ="{{variable.attachment.url}}"> {{variable.attachment}}</a></p>
对于您的代码:
class model_name(models.Model):附件= models.FileField()
附件
是一个 FileField
对象,它具有一个名为 filename
的属性,因此只需索取该属性即可.即
foo = model_name.objects.create(attachment = some_file)foo.attachment.filename#以字符串形式返回文件名
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:
- Have it display a different name, not a url.
- 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>
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
这篇关于Django:显示上传文件的文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!