使用Django从模型中显示图像

0 投票
2 回答
981 浏览
提问于 2025-04-18 04:14

我想在我的主页上显示多个图片,这些图片来自我Product模型中的图片字段。每当我添加一个带图片的新产品时,它就会生成一个新的

  • 标签,里面放着新图片。

    然后,我希望用户点击主页上的图片时,能在一个弹出窗口中显示这个图片,同时在网址中显示产品的slug名称,弹出窗口里还会显示这个Product的其他信息。

    有没有人能帮我指导一下,怎么实现这个功能呢?

    这是我目前的进展:

    谢谢大家!

    Models.py

    from __future__ import unicode_literals
    
    from django.db import models
    from django.utils.translation import ugettext_lazy as _
    
    import datetime
    
    class Designer(models.Model):
        name = models.CharField(max_length=254, blank=True, null=True)
        label_name = models.CharField(max_length=254, blank=True, null=True)
        description = models.TextField(null=True, blank=True)
        specialites = models.CharField(max_length=254,  null=True, blank=True)
        image = models.ImageField(upload_to='images/designers/main',max_length=100, null=True) #For the argument upload_to, will add to the static folder and generated image will be stored in suing that path specified
    
        #For Admin Purposes, to track and see which if still active by for administrative users only
        is_active = models.BooleanField(default=True)
    
    
        #Metadata
        class Meta:
           verbose_name = _("Designer Information")
           verbose_name_plural = _("Designers")
    
        #Helps return something meaningful, to show within the admin interface for easy interaction
        def __unicode__(self):
            return "{0} {1}".format(self.name, self.label_name)
    
    class Boutique(models.Model):
        name = models.CharField(max_length=254, blank=True, null=True)
        address = models.CharField(max_length=255, blank=True, null=True)    
        city = models.CharField(max_length=50, null=True, blank=True)
        state = models.CharField(max_length=2, null=True, blank=True)
        zipcode = models.IntegerField(max_length=5, null=True, blank=True)
        boutique_website = models.URLField(max_length=200,  null=True, blank=True)
    
        #For Admin Purposes, to track a product to see which is active by administrative users
        is_active = models.BooleanField(default=True)
    
        #Foreign Keys & other relationships
        designer = models.ForeignKey(Designer)
    
        #Metadata
        class Meta:
          verbose_name = _("Boutique Information")
          verbose_name_plural = _("Boutiques")
    
        #Helps return something meaningful, to show within the admin interface for easy interaction
        def __unicode__(self):
            return "{0}, {1}, {2}".format(self.name, self.city, self.state)
    
    class ProductCategory(models.Model):
        name = models.CharField(max_length=255L, blank=True, null=True)
        slug = models.SlugField(max_length=50, unique=True, help_text='Unique value for product page URL, created from name.')
    
        #For Admin Purposes, to track and see which if still active by for administrative users only
        is_active = models.BooleanField(default=True)
    
        #For Admin Purposes, to track when we add each product and each product was updated by administrative users
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
    
        #Metadata
        class Meta:
            verbose_name = _("Product Category")
            verbose_name_plural = _("Product Categories")
    
        #Helps return something meaningful, to show within the admin interface for easy interaction
        def __unicode__(self):
            return "{0}".format(self.name)
    
    class Product(models.Model):
        name = models.CharField(max_length=254, blank=True, null=True)
        description = models.TextField(blank=True, null=True)    
        color_name = models.CharField(max_length=254, null=True, blank=True)
        size_types = models.CharField(max_length=7, null=True, blank=True)
        product_price = models.DecimalField(max_digits=9,decimal_places=2)
        old_price = models.DecimalField(max_digits=9,decimal_places=2, blank=True,default=0.00) #To show original price if, new price has been added
        product_tags = models.CharField(max_length=254, null=True, blank=True, help_text='Comma-delimited set of SEO keywords for product tag area')
        novelty = models.CharField(max_length=254, null=True, blank=True)
        product_website = models.URLField(max_length=200,  null=True, blank=True) #To show other sites to Users, where they can purchase the particular product
        image = models.ImageField(upload_to='images/products/main',max_length=100, null=True) #For the argument upload_to, will add to the static folder and generated image will be stored in suing that path specified
        slug = models.SlugField(max_length=255, unique=True, help_text='Unique value for product page URL, created from name.')
    
      #This shows when each item was uploaded & by who, to the User 
        uploaded_by = models.CharField(max_length=254, blank=True, null=True)
        uploaded_at = models.DateTimeField(auto_now=True)
    
      #For Admin Purposes, to track and see which if still active by for administrative users only
        is_active = models.BooleanField(default=True)
    
        #Foreign Keys & other relationships
        designer = models.ForeignKey(Designer)
        boutique = models.ForeignKey(Boutique)
        category = models.ForeignKey(ProductCategory)
    
        #Metadata
        class Meta:
            verbose_name = _("Product")
            verbose_name_plural = _("Products")
    
        #Helps return something meaningful, to show within the admin interface for easy interaction
        def __unicode__(self):
            return "{0}".format(self.name)
    

    Admin.py

    from __future__ import unicode_literals
    
    from django.contrib import admin
    from products.models import Designer, Product, ProductCategory, Boutique
    
    
    class DesignerAdmin(admin.ModelAdmin):
    
        list_display = ["name", "label_name", "description", "specialites", "image", "is_active"]
        search_fields = ["name", "label_name"]
        list_per_page = 50
    
    class ProductAdmin(admin.ModelAdmin):
    
        list_display = ["name", "description", "color_name", "size_types", "product_price", "old_price", "product_tags", "novelty","product_website", "image", "slug", "uploaded_by", "uploaded_at", "is_active"]
        search_fields = ["name", "product_price"]
        list_per_page = 25
    
    class ProductCategoryAdmin(admin.ModelAdmin): 
    
        list_display = ["name", "slug", "is_active", "created_at", "updated_at"]
        search_fields = ["name"]
        list_per_page = 25
    
    class BoutiqueAdmin(admin.ModelAdmin):
    
        list_display = ["name", "address", "city", "state", "zipcode", "boutique_website", "is_active"]
        search_fields = ["name"]
        list_per_page = 10
    
    
    #Register Models below
    admin.site.register(Boutique, BoutiqueAdmin)
    admin.site.register(Designer, DesignerAdmin)
    admin.site.register(Product, ProductAdmin)
    admin.site.register(ProductCategory, ProductCategoryAdmin)
    

    Forms.py

    from __future__ import unicode_literals
    
    from django import forms
    
    from django.forms import extras, ModelForm
    
    from products.models import Designer, Product, ProductCategory, Boutique
    
    class DesignerForm(ModelForm):
        class Meta:
            model = Designer
    
    class ProductForm(ModelForm):
        class Meta:
            model = Product
    
    class BoutiqueForm(ModelForm):
        class Meta:
            model = Boutique
    
    class ProductCategoryForm(ModelForm):
        class Meta:
            model = ProductCategory
    

    Views.Py

    from __future__ import unicode_literals
    
    from django.http import Http404, HttpResponseForbidden
    from django.shortcuts import redirect, get_object_or_404
    from django.core.urlresolvers import reverse
    from django.utils.translation import ugettext_lazy as _
    from django.views.generic import DetailView
    
    from django.contrib import auth, messages
    from django.contrib.sites.models import get_current_site
    from django.shortcuts import render
    
    from products.forms import ProductForm, ProductCategoryForm
    from products.forms import BoutiqueForm
    from products.forms import DesignerForm
    
    from products.models import Boutique, Product, ProductCategory, Designer
    
    
    class ProductView(DetailView):
        model = Product
    

    主页模板

    {% extends "site_base.html" %}
       {% load i18n %}
        {% block body %}
            <div id="main" role="main">
                <ul id="tiles">
                    <li>
                       <img src=" {{ object.image.url }}" />
                    </li>         
                 </ul>
            </div>
        {% endblock %}
    

    urls.py

        from django.conf.urls import patterns, include, url
    from django.conf import settings
    from django.conf.urls.static import static
    from django.views.generic import TemplateView
    from products.views import ProductView
    
    from django.contrib import admin
    
    
    urlpatterns = patterns('',
        url(r"^$", TemplateView.as_view(template_name="homepage.html"), name="home"),
        url(r"^$", ProductView.as_view(), name="list"),
    )
    
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
    
  • 2 个回答

    0

    在我看来,你的问题出在如何访问视图中的内容。如果你使用的是表单视图,那么你应该可以通过 {{ form....}} 来获取数据(比如 {{form.image.url}})。

    如果你能获取到对象,并且没有重新定义它的别名,那么你应该可以通过 {{ object.... }} 来访问它。

    0

    你可以在你的 settings.py 文件里设置 MEDIA_URL,然后用 <img src="{{ MEDIA_URL }}{{ product.image.url }}" /> 这个代码来显示图片。

    撰写回答