Найти - Пользователи
Полная версия: как добавить превьюшки картинок в админка?
Начало » Django » как добавить превьюшки картинок в админка?
1
palzuncoff
Здравствуйте, не могу понять как просматривать загруженные картинки из админки

вот модели

 from __future__ import unicode_literals
from django.db import models
from django.db.models import ImageField
from cornelshop.settings import MEDIA_ROOT
import os
def get_image_path(instance, filename):
    return os.path.join(MEDIA_ROOT, 'img/')
class Product(models.Model):
    product_name=models.CharField(max_length=900)
    product_image = models.ImageField(upload_to=get_image_path, blank=True, null=True)
    product_price=models.FloatField(max_length=10)
    product_discaunt=models.CharField(max_length=5, blank=True)
    product_category=models.CharField(max_length=1000)
    product_discription=models.TextField(max_length=1000)
    def __unicode__(self):
        return self.product_discription
    def __unicode__(self):
        return self.product_category
    def __unicode__(self):
        return self.product_name
    def image_img(self):
        if self.product_image:
            return u'<a href="{0}" target="_blank"><img src="{0}" width="100"/></a>'.format(self.product_image.url)
        else:
            return '(no picture)'
    image_img.short_description = 'Picture'
    image_img.allow_tags = True
    class Meta:
        verbose_name='Product'
        verbose_name_plural='Products'
        ordering= ('product_name',)

вот urls

 from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.views import serve
urlpatterns = [
    url(r'^store/', include('store.urls')),
    url(r'^admin/', admin.site.urls),
    url(r'^media/(?P<path>.*)$', serve, {
    'document_root': settings.MEDIA_ROOT,
}),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

вот admin.py

 from django.contrib import admin
from .models import Product
class ProductAdmin(admin.ModelAdmin):
    list_display = ('product_name','product_image', 'image_img','product_price', 'product_category', )
    readonly_fields = ['image_img',]
    fields=('product_name','product_image', 'image_img','product_price', 'product_category', )
"""
    def image_tag(self, obj):
        return '<img src="%s">' % obj.product_image.url
    image_tag.allow_tags = True
"""
admin.site.register(Product, ProductAdmin)

вот settings.py

 import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
_PATH = os.path.abspath(os.path.dirname(__file__))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'n*z%jd=glbmjtvl@ddotfrx_9-qep9f+clsgle^%p^^@z0ar=a'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'store',
]
MIDDLEWARE_CLASSES = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'cornelshop.urls'
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
WSGI_APPLICATION = 'cornelshop.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.10/ref/settings/#databases
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'cornelshop',
        'USER': 'root',
        'PASSWORD': '297604200'
    }
}
# Password validation
# https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]
# Internationalization
# https://docs.djangoproject.com/en/1.10/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Chisinau'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(_PATH, 'media')
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash if there is a path component (optional in other cases).
# Examples: "http://media.lawrence.com", "http://example.com/media/"
MEDIA_URL = '/media/'
#STATIC_ROOT = os.path.join(_PATH, 'static')
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.10/howto/static-files/
STATIC_URL = '/static/'
"""
STATICFILES_DIRS = (
   os.path.join(_PATH, 'static'),
)
"""
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)
ADMIN_MEDIA_PREFIX = '/static/admin/'


вот собственно ошибка

Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/img/i-should-buy-a-boat.jpg
Raised by: django.contrib.staticfiles.views.serve

Ateros
Ну а на диске где лежит файл i-should-buy-a-boat.jpg ?
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB