【发布时间】:2021-01-19 03:53:35
【问题描述】:
我之前发布了类似的内容,但无法找到合适的解决方案。我正在努力解决的一件事是能够在 DJANGO html 模板中提供静态路径/文件引用。希望通过发布另一个问题,我将能够理解这是如何工作的。做了一些研究并通读了 DJANGO 文档,但无法找到涵盖我的场景的内容。
我们开始吧:
在我的模型中,我使用路径引用字段
class Product_images(models.Model):
product = models.ForeignKey(Products, on_delete=models.SET_NULL, blank=True, null=True)
path_to_image = models.CharField(max_length=150,null=True, blank=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)
该字段的值设置为(示例): static\images\Product\PowerBI\Receivables\Receivables 6.png
文件物理存储在应用程序 Main/static/....
我的设置文件包含:
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'Main/')
MEDIA_URL = '/Main/'
然后我在应用程序中有两个模板,我想在其中提供这些图像。一个页面通过以下方式使用自定义上下文处理器:
{{ product_section }}
返回的html包括:
html_value += u'<img class="d-block w-100" src="{}" width="400px" height="250x" alt="{}">'.format(productimages_obj.path_to_image,productimages_obj.name)
此上下文处理器标记在 products_view 视图函数返回的模板中使用。
现在,我想在另一个视图 gallery_view 中使用相同的图像:
def gallery_view(request, requestid, *arg, **kwargs):
productimages = Product_images.objects.filter(product=requestid)
if productimages.exists() != True:
return HttpResponseNotFound('<h1>Page not found</h1>')
context = {
'productimages': productimages
}
return render(request, "gallery.html", context)
当使用以下模板标签 {{ productimages.path_to_image }} 我得到 404 "GET /Gallery/static/images/Product/PowerBI/Finance/Finance%207.png HTTP/1.1" 404 3485。
模板编码如下:
<section id="gallery" class="bg-light">
<div class="container-fluid">
<div class="row">
{% for productimages in productimages %}
<div class="col-md">
<img src="{{ productimages.path_to_image }}" onclick="openModal();currentSlide({{ forloop.counter }})" class="hover-shadow">
</div>
{% endfor %}
</div>
</div>
最后但并非最不重要的 Urls.py:
urlpatterns = [
path('', views.home_view, name='home'),
path('Home', views.home_view, name='home'),
path('PowerBI', views.products_view, name='power bi'),
path('Services', views.services_view, name='services'),
path('About', views.about_view, name='about'),
path('Contact', views.contact_view, name='contact'),
path('Gallery/<int:requestid>', views.gallery_view, name='gallery'),
] + 静态(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
我在这里犯了什么错误?为什么 GET 在 URL 中包含 /Gallery/?我该如何规避这种情况?
谢谢大家。
【问题讨论】:
标签: django