python - 尝试访问 Django 应用程序中上传的文件时出错
问题描述
我有一个 Django 应用程序,我正在上传一些 json 文件。尝试访问这些文件时出现 404(未找到)错误。
这些文件将加载到 OpenLayers 层中。如果我在项目静态文件中使用 json 它工作正常。
文件正确上传到项目文件夹中的“uploaded_files”目录。但是当试图通过 object.file.url 访问 html 页面中的这些文件时,我总是会出错。
如果我将 MEDIA_URL 更改为“/uploaded_files/”,则会出现错误,因为它希望找到 core/ 或 admin/ url。
示例: http: //127.0.0.1 :8000/uploaded_files/file.json
设置.py 文件:
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]
MEDIA_URL = '/core/uploaded_files/' # core is the application in django project. I have admin and core applications.
MEDIA_ROOT = os.path.join(BASE_DIR, 'uploaded_files')
urls.py 文件:
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
模型.py 文件:
def get_upload_file_name(instance, filename):
return "%s_%s" % (str(time()).replace('.', '_'), filename)
class Estado(models.Model):
estado = models.CharField(max_length=2)
def __str__(self):
return self.estado
class TipoFile(models.Model):
tipo = models.CharField(max_length=50)
def __str__(self):
return self.tipo
class FileEstadoMunicipio(models.Model):
estado = models.ForeignKey(Estado, on_delete=models.CASCADE, null=False)
municipio = models.CharField(max_length=100, null=False)
tipo = models.ForeignKey(TipoFile, on_delete=models.CASCADE, null=False)
dat_criacao = models.TimeField(default=datetime.datetime.now(), null=False)
file = models.FileField(upload_to=get_upload_file_name, null=False)
.html 文件:
{% load static %}
var layer = new ol.layer.Vector({
source: new ol.source.Vector({
format: new ol.format.GeoJSON({dataProjection: 'EPSG:32722'}),
url: '{{ alagamento.file.url }}'
# url: '{% static "jsonfiles/cadastro_eixos_logradouros.json" %}' works fine
}),
style: style,
opacity: 0.3
});
在 html 页面中出现错误:
获取http://127.0.0.1:8000/core/uploaded_files/1562551137_926604_SuscetibilidadeMovimentoDeMassa.json 404(未找到)
如果您发现我做错了什么,请告知。
解决方案
推荐阅读
- json - 作为 Json 反序列化
- gitlab - 如何设置 Slack 频道以直接链接到 GitLab 问题和合并请求?
- javascript - NgForm 的属性“有效”在 HTML 中为假,但在组件中为真
- android - 我们如何以编程方式控制辅助显示器中的屏幕方向?
- c# - 将 xaml 用于 xamarin forns 项目时出现错误,并且在呈现控件时出现异常
- r - “点图”相对于具有标准偏差的平均值
- matlab - 实验数据的数值积分
- python - Django 删除 OneToOneField
- javafx - 如何在javafx中绘制一个开放的弧?
- android - 视图周围的渐变阴影