使用Django从模型显示图像

时间:2014-04-25 14:30:19

标签: python ajax django

所以我想在我的主页上使用我Product模型的图像字段中的数据显示多个图像。前提是每次我添加带有图像的新产品时,它都会生成带有新图像的新li标签。

然后我希望当用户点击主页上的图像时,它会显示在模型窗口中,其中包含URL中产品的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 :(得分:0)

您可以在MEDIA_URL中设置settings.py,然后使用<img src="{{ MEDIA_URL }}{{ product.image.url }}" />

答案 1 :(得分:0)

恕我直言,您遇到了如何访问视图中内容的问题。如果您使用的是表单视图,则应通过{{ form....}}(例如{{form.image.url}})获取数据。

如果您有可用的对象且尚未重新定义其别名,则应通过{{ object.... }}获取该对象。