假设请求中的URL是用于已知静态文件的,那么如何确定哪个模型实例引用了该文件
如果我有几个不同的Django模型,每个模型都有一个ImageField,那么这些字段都知道如何在文件系统上存储一个相对路径:
# models.py
from django.db import models
class Lorem(models.Model):
name = models.CharField(max_length=200)
secret_icon = models.ImageField(upload_to='secrets')
secret_banner = models.ImageField(upload_to='secrets')
class UserProfile(models.Model):
user = models.ForeignKey(User)
secret_image = models.ImageField(upload_to='secrets')然后,模板可以使用(例如) instance.secret_banner.url属性呈现这些图像。
当同一个URL的请求出现时,我希望在视图中处理该请求:
# urls.py
from django.urls import path
from .views import StaticImageView
urlpatterns = [
...,
path(settings.MEDIA_URL + 'secrets/<path:relpath>', StaticImageView.as_view(), name='static-image'),
]因此,StaticImageView.get方法将被传递从URL解析的relpath参数。
在这一点上,我需要做更多的处理,基于哪个实例为这个静态映像创建URL。
# views.py
from django.views.generic import View
class StaticImageView(View):
def get(self, request, relpath):
instance = figure_out_the_model_instance_from_url_relpath(relpath)
do_more_with(instance)我不知道的是如何编写figure_out_the_model_instance_from_url_relpath代码。
我如何使用路径来找到生成的模型和实例?
发布于 2020-09-03 06:24:20
您可以从图像文件,或者更确切地说,从图像的文件名中查询和获取实例。首先从relpath获取文件名,然后查询实例。
示例代码示例:
class StaticImageView(View):
def get(self, request, relpath):
fname = get_filename_from_relpath(relpath)
instance = Lorem.objects.get(secret_icon=fname)
do_more_with_instance(instance)我以为你想要基于secret_icon图像。您可以根据需要更改它。
https://stackoverflow.com/questions/63717788
复制相似问题