Python 如何在Django中从图像模型获取图像到主页?

Python 如何在Django中从图像模型获取图像到主页?,python,django,django-models,django-views,django-templates,Python,Django,Django Models,Django Views,Django Templates,我正在开发一个电子商务网站与Django。在我的主页上显示了如下图所示的产品卡 我从我的产品模型(图像字段)中取出的每张卡片上都有此产品图像。当我将鼠标悬停在主页上的该图像上时,该图像正在更改为另一图像。这是因为我需要另一张图片,我想从我的产品图片模型中获取下一张图片(悬停时显示)。但我不知道怎么做 url.py from django.urls import path from . import views from django.conf.urls.static import static

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

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

url.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'),
]
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)
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'

型号.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'),
]
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)
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 我的模板文件是一个非常大的文件,所以我只在从产品模型中获取图像的位置插入元素(这个代码很好),但我不知道如何编写代码从我的产品图像模型中获取图像

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

更改HTML中的src

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

我假设您的设置中有
MEDIA\u URL=/MEDIA/
。如果您有不同的
MEDIA\u URL

首先,在您的模型中,您可以给出一个相关的\u 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 %}
这将对查询集从最初创建到最后进行排序。如果不想添加时间创建字段,也可以选择按id排序

方法2:

将属性添加到产品模型中:

    class Product:
           ....
    @property
    def sorted_image_set(self):
        return self.product_images.order_by('time_created')
然后可以从模板访问此属性

  {% for image in product.sorted_image_set %}
方法3:

创建自定义模板标记以支持模板中的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" %}

在对列表进行排序后,您只需通过数组索引即可访问它,例如图像[0]或图像[1]

我编写的html代码运行良好,您如何在我的产品模型问题中的图像中看到我已经毫无问题地拍摄了图像。但我不知道如何从我的产品图片模型中获取图片到我的home.html文件。非常感谢,我已经用你们的答案解决了这个问题。我还想问你。使用模板中的代码{{image.image.url}},我可以在我的产品图像模型中获得最后添加的图像,但是如何在产品图像模型中获得第二个图像或第一个图像。提前谢谢。