【问题标题】:How get image from images model to home page in Django?如何从图像模型中获取图像到 Django 的主页?
【发布时间】:2020-10-29 13:30:44
【问题描述】:

我正在使用 Django 开发一个电子商务网站。在我的主页中显示了产品卡片,如下图所示。

我从我的产品模型(图像字段)中获取的每张卡片中的此产品图像。当我将鼠标悬停在主页上的此图像上时,该图像正在更改为另一个图像。那是因为我需要另一个图像,并且我想从我的 Product_images 模型中获取下一个图像(当我悬停时显示)。但我不知道该怎么做。

urls.py

from django.urls import path
from . import views
from django.conf.urls.static import static

urlpatterns = 
    path('', views.home_page, name='amd-home'),
    path('product/<int:id>/', views.product_detail, name='product-detail'),
    path('about/', views.about, name='amd-about'),
]

views.py

from django.shortcuts import render, get_object_or_404
from django.views.generic import ListView, DetailView
from django.http import HttpResponse
from .models import Product, Product_image, Product_details

def home_page(request):
    products = Product.objects.all()
    images = Product_image.objects.all()
    context = {'products':products, 'images':images}
    return render(request, 'product/home.html', context)

models.py

from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User

class Category(models.Model):
    name = models.CharField(max_length=200)
    parent_id = models.IntegerField(default=0)
    description = models.TextField()
    image = models.ImageField(upload_to='uploads/')

    def __str__(self):
        return f'{self.name}'

class Brand(models.Model):
    name = models.CharField(max_length=200)
    description = models.CharField(max_length=400)
    image = models.ImageField(upload_to='uploads/')

    def __str__(self):
        return f'{self.name}'

class Product(models.Model):
    title = models.CharField(max_length=200)
    image = models.ImageField(upload_to='uploads/', blank=True, null=True)
    sku = models.CharField(max_length=200)
    price = models.IntegerField(default=0)
    price_old = models.IntegerField(default=0)
    description = models.TextField()
    status = models.BooleanField(default=False)
    date_posted = models.DateTimeField(auto_now_add=True)
    internal_storage = models.CharField(max_length=50, blank=True, null=True, default=None)
    ram = models.CharField(max_length=50, blank=True, null=True, default=None)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    brand = models.ForeignKey(Brand, on_delete=models.CASCADE)
    category = models.ForeignKey(Category, on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.title}, {self.description}'

class Product_image(models.Model):
    image = models.ImageField(upload_to='uploads/')
    product = models.ForeignKey(Product, on_delete=models.CASCADE)

    def __str__(self):
        return f'{self.product.title} image'

home.html 我的模板文件是一个非常大的文件,所以我只插入从 Product 模型中获取图像的元素(这个代码字很好),但我不知道如何编写代码来从我的 Product_image 模型中获取图像。

{% for product in products %}
 <a href="{% url 'product-detail' product.id %}"><img alt="" src="{{ product.image.url }}"></a>
{% endfor %}

【问题讨论】:

    标签: python django django-models django-views django-templates


    【解决方案1】:

    首先,在您的模型中,您可以提供一个 related_name 字段,例如:

    class Product_image(models.Model):
        image = models.ImageField(upload_to='uploads/')
        product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images)
    
        def __str__(self):
            return f'{self.product.title} image'
    

    然后您可以在模板中访问产品的图像,例如:

    {% for product in products %}
         <a href="{% url 'product-detail' product.id %}"> </a>
     {% for image in product.product_images.all %}
        <img alt="" src="{{ image.image.url }}">
     {% endfor %}
    {% endfor %}
    

    PS:您不必从视图中返回所有 Product_image 查询集

    扩展答案,如果您想订购图像,您可以采取不同的方法:

    方法一:

    class Product_image(models.Model):
        image = models.ImageField(upload_to='uploads/')
        product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="product_images)
        time_created = models.DateTimeField(null=True, blank=True)
    
        def __str__(self):
            return f'{self.product.title} image'
       
        class Meta:
            ordering = ['time_created'] 
    

    这会将查询集从 first created 到 last 排序。如果您不想添加时间创建字段,也可以选择按 id 排序。

    方法二:

    为您的产品模型添加一个属性:

        class Product:
               ....
        @property
        def sorted_image_set(self):
            return self.product_images.order_by('time_created')
    

    然后你可以从模板中访问这个属性

      {% for image in product.sorted_image_set %}
    

    方法三:

    创建自定义模板标签以支持模板中的 order_by

    @register.filter
    def order_by(queryset, args):
        args = [x.strip() for x in args.split(',')]
        return queryset.order_by(*args)
    

    那么你可以这样做:

    {% for image in product.product_images|order_by:"time_created" %}
    

    列表排序后,您可以通过数组索引访问它,例如 images[0] 或 images[1]

    【讨论】:

    • 非常感谢,我已经解决了你的问题。我还想问你。在我的模板中使用此代码 {{ image.image.url }} 我将最后添加的图像添加到我的 Product_image 模型中,但是如何在 Product_image 模型中获得第二张图像或第一张图像。提前致谢。
    【解决方案2】:

    更改 HTML 中的 src

    {% for product in products %}
       <a href="{% url 'product-detail' product.id %}"><img alt="" src="/media/uploads/{{ 
       product.image }}"></a>
    {% endfor %}
    

    我假设您的设置中有MEDIA_URL=/media/。如果您有不同的MEDIA_URL,请在 src 中更改它

    【讨论】:

    • 我编写的 html 代码工作正常,您如何在我的产品模型问题中看到图像我已经毫无问题地拍摄了图像。但我不知道如何从我的 Product_image 模型中获取图像到我的 home.html 文件中。
    猜你喜欢
    • 2018-11-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    • 1970-01-01
    • 1970-01-01
    • 2021-10-24
    • 2016-01-24
    • 1970-01-01
    相关资源
    最近更新 更多