更新时间:2022-10-15 12:03:55
对于您的代码:
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:
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