简体   繁体   中英

Displaying images from model using Django

So I would like to simply show multiple images on my homepage with data from the image field of my Product model. The premise is every time I add a new Product with an image it would generate a new li tag with a new image.

I then would like when the user clicks on the image on the homepage it appears in a model window with the slug name of the product in the URL, with the rest of the Product Information throughout the template that appears in the model window.

So can anyone help guide me on how to implement this solution?

Here is what I have so far:

Thank You!

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

Template For Homepage

{% 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)

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

IMHO you have a problem of how you access the content in the view. If you're using the formview, you should have the data available via {{ form....}} (eg {{form.image.url}} ).

If you have the object available and you haven't redefined its alias, then you should have it via {{ object.... }} .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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