是否可以使用模板中Django中上传的文件?

发布于 2025-02-08 19:21:28 字数 287 浏览 0 评论 0原文

我有一个Django模型表格,在其中我上传了应用程序的图像。我只是在本地暂时存储它们,因为它不是一个真正的项目。看上去像这样,我想知道是否有一种方法可以使用模板中每个对象上传的图像。我找不到任何文章。如何链接到与哪些模型相关联的图像?

I have a django model form where I uploaded images for my app. I am just storing them temporarily locally since its not a real project. The Admin looks like this I'm wondering if there is a way to use the images uploaded with each object in the template. I cant find any articles. How can I make a link to what images are associated with what models?

enter image description here

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

风向决定发型 2025-02-15 19:21:28

是的,您可以通过object.photo访问它。 url

我会向您展示一些随机示例。

由于我看不到您的模型的名称,所以让我们假装它称为帖子。

在views.py中,您可以将帖子对象发送到模板(我想您可能已经知道这一点)

view.py |示例片段

from django.views.generic import TemplateView
from .models import Post
    

class IndexView(TemplateView):
    template_name = 'yourapp/index.html'
        
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['posts'] = Post.objects.all()
        return context

,然后您可以在模板中显示如下

index.html |示例片段

{% for post in posts %}
   <img src="{{ post.photo.url }}" alt="..." class="..." />
{% endfor %}

Yes you can access it through object.photo.url

I'll show u some random example.

Since I can't see the name of your model, let's pretend that it's called Post.

In views.py you can send your post objects to the templates (I guess you probably know this already)

view.py | example snippet

from django.views.generic import TemplateView
from .models import Post
    

class IndexView(TemplateView):
    template_name = 'yourapp/index.html'
        
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['posts'] = Post.objects.all()
        return context

and then you could display it in the templates as following

index.html | example snippet

{% for post in posts %}
   <img src="{{ post.photo.url }}" alt="..." class="..." />
{% endfor %}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文