我正在构建一个应允许用户使用Django上传和下载文件的应用程序。
我有一个存储文件的模型:
class Document(models.Model):
description = models.CharField(max_length=255, blank=True)
unit_code = models.CharField(max_length=6)
input = models.FileField(upload_to='documents/')
uploaded_at = models.DateTimeField(auto_now_add=True)
@property
def filename(self):
return os.path.basename(self.document.name)
我可以从我的视图中显示模板中已上传文件的列表,如下所示:
def Document(request, str):
documents = Document.objects.filter(unit_code=str)
而在模板看到一个锚标记下载使用URL中的文件在这里:
{% for document in documents %}
{{document.filename}}<a href="{{document.input.url}}"> Download Document </a>
{% endfor %}
现在我找不到错误页面(URL指向127.0.0.1:8000/media/documents/file_name
是否可以在Django开发服务器上使用anchor标签下载文件?
假设您已正确设置MEDIA_ROOT和MEDIA_URL设置,则需要在urls.py中添加类似内容
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
重要提示:此解决方案仅在开发期间有效。对于生产,您的媒体文件应直接从Nginx(或您使用的任何Web服务器)提供,而不是通过Django提供
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句