遇到一个超出我能力范围的有趣问题。搜索了整个 interwebz 但找不到合适的东西。我们开始吧。
问题: GET 图像文件返回 404。在这种特殊情况下,文件是使用模型文件字段上传的。从模板进行的调用与文件的物理位置不同,即 404。由于应用程序的动态模式,我很困惑如何处理这个问题。简而言之,我需要一些帮助?!?!
Python Django 最新版本,良好的开始。
项目:我的网站
应用程序:主要
型号:
class Product_images(models.Model):
product = models.ForeignKey(Products, on_delete=models.SET_NULL, blank=True, null=True)
image = models.FileField(upload_to='productimages/', null=True)
name = models.CharField(max_length=50,unique=False,blank=True)
class Meta:
verbose_name = 'Product Image'
verbose_name_plural = 'Product Images'
def __str__(self):
return '{} - {} - {}'.format(self.pk, self.product, self.name)
查看:
def products_view(request, *args, **kwargs):
return render(request, "products.html")
产品.html:
包括标签 {{ Product_section }}
context_processors.py:
这里有很多循环和编码,重要的是。
html_value += u'<img class="d-block w-100" onclick="openModal();currentSlide(1)" src="{}" width="400px" height="250x" alt="{}">'.format(productimages_obj.image,productimages_obj.name)
productimages_obj 是查询集
html 值在 products.html 模板中使用
url.py:
urlpatterns = [
path('home/', views.home_view, name='home'),
path('products/someproduct', views.products_view, name='some product'),
]
结果:
http://127.0.0.1:8000/products/someproduct [2020 年 9 月 12 日 01:02:37]“获取/products/productimages/Finance1.png HTTP/1.1”404 3228
我明白为什么获取失败了。就像模型文件字段将图像存储在 main\productimages 下一样。我无法理解的是如何忽略/product/url 前缀。
想了解为什么 django 会这样做。为什么要加上前缀 url?我应该如何构建我的应用程序来规避这个问题?
干杯。
最佳答案
这段代码:
image = models.FileField(upload_to='productimages/', null=True)
将文件上传到 MEDIA_ROOT/productimages
。因此,您需要确保在 settings.py
中设置了 MEDIA_ROOT
:
MEDIA_ROOT = '/path/to/products/'
MEDIA_URL = '/products/'
然后,在urls.py
中:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
如果您想在模板中使用 {{ MEDIA_URL }}
,请在 TEMPLATES 的 'context_processors' 选项中添加 'django.template.context_processors.media'。示例:
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.media',
],
},
},
]
MEDIA_xxx
通常保留用于用户上传的图像。阅读更多内容:
关于Python Django 文件字段 404,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63855792/