简体   繁体   English

如何通过 object id 获取图像? (姜戈)

[英]How do I get image by object id? (Django)

I'm trying to get images for an object filtered by the object's id, but for now, I don't even see any request to it in my MySQL database.我正在尝试获取由对象的 id 过滤的 object 的图像,但现在,我什至在我的 MySQL 数据库中都没有看到对它的任何请求。 The snippets of my code are below.我的代码片段如下。

models.py:模型.py:

class Media(models.Model):
   word = models.ForeignKey(Word, on_delete=models.CASCADE)
   title = models.TextField(max_length=100, null=True)
   image = models.ImageField(upload_to='images/')

views.py:视图.py:

class MediaListView(generic.ListView):
   model = Media
   template_name = 'dictionaty_web/index.html'
   context_object_name = 'images'

   def get_queryset(self):
       return Media.objects.filter(word=self.request.resolver_match.kwargs['pk'])

urls.py:网址.py:

  urlpatterns = [
             path('languages/<int:pk>/', views.WordMapListView.as_view(), name='wordmaps'),
  ]

  urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

index.html:索引.html:

  {% for word in words %}
    <div class="col-sm text-center">
        <div class="card" style="width: 18rem;">
            <img scr="{{ MEDIA_URL }}{{ image.image.url }}">
            <div class="card-body">
                <h5 class="card-title">{{ word.value }}</h5>
                <a href="{% url 'dictionaty_web:detail' word.language.id word.word.id %}" class="stretched-link"></a>
            </div>
        </div>
    </div>
{% endfor %}

Your urls.py is also important when serving images in django.在 django 中提供图像时,您的 urls.py 也很重要。

do you have imported in your urls.py the following code您是否已在 urls.py 中导入以下代码

from django.conf import settings
from django.conf.urls.static import static

urlpatterns=[
    path('url/', name_of_view, name = 'url_name'),
]

if settings.DEBUG:
        urlpatterns += static(settings.MEDIA_URL,
                              document_root=settings.MEDIA_ROOT)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM