2013-08-22 3 views
0

Я пытаюсь загрузить изображение через панель администратора Django. Если я вставляю изображение через скрипт, он работает хорошо, но если я использую панель администратора Django, это не вместо.Загрузка изображения через панель администратора Django не работает

http://localhost:8000/images/100bestbuy.jpg/

использует http://localhost:8000/bcadmin/flipdiscountApp/stores/images/100bestbuy.jpg/

settings.py:

from os import path 
#------------------------------------------------------------------------------ 

DEBUG = True 
TEMPLATE_DEBUG = DEBUG 
THUMBNAIL_DEBUG = True 
HOST_NAME = 'XXXXXXXXXXXX' 
# Port for sending e-mail. 
EMAIL_PORT = 587 
EMAIL_USE_TLS = True 
# Host for sending e-mail. 
EMAIL_HOST = 'smtp.gmail.com' 
# Optional SMTP authentication information for EMAIL_HOST. 
EMAIL_HOST_PASSWORD = 'XXXXXXXXXXX' 
EMAIL_HOST_USER = 'XXXXXXXXXXXXXXXXXX' 
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' 
PROJECT_DIR_PATH = path.dirname(path.dirname(__file__)) 

ADMINS = (
) 

MANAGERS = ADMINS 

DATABASES = { 
    'default': { 
     'ENGINE': 'django.db.backends.mysql',   # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 
     'NAME': 'xxxxx',      # Or path to database file if using sqlite3. 
     'USER': 'xxxxxxx',        # Not used with sqlite3. 
     'PASSWORD': 'xxxxxxxxxx',      # Not used with sqlite3. 
     'HOST': 'localhost',       # Set to empty string for localhost. Not used with sqlite3. 
     'PORT': '',          # Set to empty string for default. Not used with sqlite3. 
    } 
} 

# Hosts/domain names that are valid for this site; required if DEBUG is False 
# See https://docs.djangoproject.com/en/1.4/ref/settings/#allowed-hosts 
ALLOWED_HOSTS = [HOST_NAME] 

# Local time zone for this installation. Choices can be found here: 
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name 
# although not all choices may be available on all operating systems. 
# In a Windows environment this must be set to your system time zone. 
TIME_ZONE = 'America/Chicago' 

# Language code for this installation. All choices can be found here: 
# http://www.i18nguy.com/unicode/language-identifiers.html 
LANGUAGE_CODE = 'en-us' 

SITE_ID = 1 

# If you set this to False, Django will make some optimizations so as not 
# to load the internationalization machinery. 
USE_I18N = True 

# If you set this to False, Django will not format dates, numbers and 
# calendars according to the current locale. 
USE_L10N = True 

# If you set this to False, Django will not use timezone-aware datetimes. 
USE_TZ = True 

# Absolute filesystem path to the directory that will hold user-uploaded files. 
# Example: "/home/media/media.lawrence.com/media/" 
MEDIA_ROOT = PROJECT_DIR_PATH + "/flipdiscountApp/" 

# URL that handles the media served from MEDIA_ROOT. Make sure to use a 
# trailing slash. 
# Examples: "http://media.lawrence.com/media/", "http://example.com/media/" 
MEDIA_URL = PROJECT_DIR_PATH + "/flipdiscountApp/images/" 

# Absolute path to the directory static files should be collected to. 
# Don't put anything in this directory yourself; store your static files 
# in apps' "static/" subdirectories and in STATICFILES_DIRS. 
# Example: "/home/media/media.lawrence.com/static/" 
STATIC_ROOT = '' 

# URL prefix for static files. 
# Example: "http://media.lawrence.com/static/" 
STATIC_URL = '/static/' 

# Additional locations of static files 
STATICFILES_DIRS = (
    # Put strings here, like "/home/html/static" or "C:/www/django/static". 
    # Always use forward slashes, even on Windows. 
    # Don't forget to use absolute paths, not relative paths. 
) 

# List of finder classes that know how to find static files in 
# various locations. 
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder', 
    'django.contrib.staticfiles.finders.AppDirectoriesFinder', 
# 'django.contrib.staticfiles.finders.DefaultStorageFinder', 
) 

# Make this unique, and don't share it with anybody. 
SECRET_KEY = '80$5!%+y1ukk624dh5a539+39c3ll08$ketf=&0ovq-=znb)2-' 

# List of callables that know how to import templates from various sources. 
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader', 
    'django.template.loaders.app_directories.Loader', 
#  'django.template.loaders.eggs.Loader', 
) 

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware', 
    'django.contrib.sessions.middleware.SessionMiddleware', 
    'django.middleware.csrf.CsrfViewMiddleware', 
    'django.contrib.auth.middleware.AuthenticationMiddleware', 
    'django.contrib.messages.middleware.MessageMiddleware', 
    # Uncomment the next line for simple clickjacking protection: 
    # 'django.middleware.clickjacking.XFrameOptionsMiddleware', 
) 

ROOT_URLCONF = 'flipdiscounts.urls' 

# Python dotted path to the WSGI application used by Django's runserver. 
WSGI_APPLICATION = 'flipdiscounts.wsgi.application' 

TEMPLATE_DIRS = (
    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". 
    # Always use forward slashes, even on Windows. 
    # Don't forget to use absolute paths, not relative paths. 
) 

INSTALLED_APPS = (
    'south', 
    'massadmin', 
    'sorl.thumbnail', 
    'flipdiscountApp', 
    'django.contrib.auth', 
    'django.contrib.sites', 
    'django.contrib.admin', 
    'django.contrib.sessions', 
    'django.contrib.messages', 
    'django.contrib.staticfiles', 
    'django.contrib.contenttypes', 
    'django.contrib.sitemaps', 
) 

# A sample logging configuration. The only tangible logging 
# performed by this configuration is to send an email to 
# the site admins on every HTTP 500 error when DEBUG=False. 
# See http://docs.djangoproject.com/en/dev/topics/logging for 
# more details on how to customize your logging configuration. 
LOGGING = { 
    'version': 1, 
    'disable_existing_loggers': False, 
    'filters': { 
     'require_debug_false': { 
      '()': 'django.utils.log.RequireDebugFalse' 
     } 
    }, 
    'handlers': { 
     'mail_admins': { 
      'level': 'ERROR', 
      'filters': ['require_debug_false'], 
      'class': 'django.utils.log.AdminEmailHandler' 
     } 
    }, 
    'loggers': { 
     'django.request': { 
      'handlers': ['mail_admins'], 
      'level': 'ERROR', 
      'propagate': True, 
     }, 
    } 
} 
#------------------------------------------------------------------------------ 

models.py

class stores(models.Model): 
    """ This is the store model """ 

    seo_url = models.URLField()               # SEO URL for flipdiscounts.in 
    storeURL = models.URLField()               # Store URL 
    fallBackURL = models.URLField()              # Fallback URL for couponURL   
    storeDescription = models.TextField()            # Store Description 
    storeTags = models.ManyToManyField(tags)            # All the tags associated with the store 
    storeName = models.CharField(max_length=30)           # Store Name 
    storeSlug = models.CharField(max_length=400)           # This is the text you see in the URL 
    updatedAt = models.DateTimeField(auto_now=True)          # Time at which store is updated 
    storeImage = models.ImageField(upload_to="images")         # Store Image 
    createdAt = models.DateTimeField(auto_now_add=True)         # Time at which store is created 
    hash = models.CharField(max_length=10,unique=True)         # Tag Hash for flipdisconts.in 
    storePopularityNumber = models.IntegerField(choices=PRIORITY_CHOICES,default=3)  # Store Popularity Number 

    def StoreImage(self): 
     """Method to return store image for admin panel""" 
     return '<img src="%s" height="150" width="150"/>' % self.storeImage 
    StoreImage.allow_tags = True 

urls.py

from django.contrib import admin 
from flipdiscountApp import views 
from flipdiscounts.settings import MEDIA_URL 
from django.conf.urls import patterns, include, url 
from flipdiscountApp.sitemaps import flipdiscountSitemap 
#------------------------------------------------------------------------------ 

sitemaps = dict(
     static = flipdiscountSitemap, 
     ) 
admin.autodiscover() 

urlpatterns = patterns('', 
    url(r'^$', views.index),                 # For index.html page      
    url(r'^stores/$', views.get_all_stores),             # For stores.html page 
    url(r'^categories/$', views.categories),             # For categories page 
    url(r'^coupon_vote/$', views.couponVote),             # To handle post request for coupon votes. 
    url(r'^couponassist/$', views.couponAssist),            # For coupon assist page 
    url(r'^bcadmin/', include(admin.site.urls)),            # For django admin page 
    url(r'^bcadmin/', include("massadmin.urls")),            # For django massadmin app      
    url(r'^search_stores/$', views.searchStores),            # For search page 
    url(r'^contact/$', views.contact,name='contact'),           # For contact.html page      
    url(r'^subscribe/$', views.subscribe,name='subscribe'),          # To handle post request for subscription submit. 
    url(r'^images/(?P<path>.*)/$', 'django.views.static.serve',         # For store image 
     {'document_root': MEDIA_URL, 'show_indexes': False}),   
    url(r'^submit_coupon/$', views.submitCoupon,name='submitCoupon'),       # To handle post request for coupon submit. 
    url(r'^(?P<seo_url>[-.\w]+)/s/(?P<hash_id>[-.\w]+)/$', views.store),      # For store template 
    url(r'^(?P<seo_url>[-.\w]+)/c/(?P<hash_id>[-.\w]+)/$', views.getTagCoupons),    # For tag related coupon template 
    url(r'^sitemap\.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}), # For flipdiscounts sitemap  
) 

#------------------------------------------------------------------------------ 

проект Dir структура:

tree -d 
. 
└── flipdiscounts 
    ├── flipdiscountApp 
    │   ├── images 
    │   ├── static 
    │   │   ├── admin 
    │   │   │   ├── css 
    │   │   │   ├── img 
    │   │   │   │   └── gis 
    │   │   │   └── js 
    │   │   │    └── admin 
    │   │   ├── css 
    │   │   │   ├── fonts 
    │   │   │   └── layerslider 
    │   │   │    ├── darkskin 
    │   │   │    ├── defaultskin 
    │   │   │    ├── glass 
    │   │   │    ├── lightskin 
    │   │   │    ├── minimal 
    │   │   │    ├── noskin 
    │   │   │    ├── portfolio 
    │   │   │    └── powerful 
    │   │   ├── docs 
    │   │   │   └── assets 
    │   │   │    ├── blueprint-css 
    │   │   │    │   ├── plugins 
    │   │   │    │   │   ├── buttons 
    │   │   │    │   │   │   └── icons 
    │   │   │    │   │   ├── fancy-type 
    │   │   │    │   │   ├── link-icons 
    │   │   │    │   │   │   └── icons 
    │   │   │    │   │   └── rtl 
    │   │   │    │   └── src 
    │   │   │    └── images 
    │   │   ├── img 
    │   │   │   ├── fancybox 
    │   │   │   ├── nivo 
    │   │   │   └── temp 
    │   │   └── js 
    │   │    └── libs 
    │   └── templates 
    └── flipdiscounts 

может кто-то помочь мне ....

+0

Ваша проблема в том, что 'MEDIA_URL' установлен неправильно. Я ответил на это, но вы должны прочитать [этот вопрос] (http://stackoverflow.com/questions/6813339/what-is-the-documented-definition-of-media-root-media-url-static-root- static) для получения дополнительной информации. –

+0

Я пробовал ваше решение, но тогда, что я должен использовать здесь 'storeImage = models.ImageField (upload_to =" images ") # Хранить изображение' пожалуйста, вы можете мне помочь ... У меня не было большого опыта работы с Django –

+0

Когда я пытаясь загрузить изображение через панель администратора Django, он загружается в нужное место, но путь, хранящийся в БД, неверен 'http: // localhost: 8000/bcadmin/flipdiscountApp/stores/108/images/images/100bestbuy.jpg /' –

ответ

0

MEDIA_URL является URL, а не путь к файлу. Вам нужно:

MEDIA_URL = "images/" 

Кроме того, необходимо изменить upload_to поле, в противном случае ваши изображения будут идти в /flipdiscountApp/images/images/.

Вы также должны использовать url property из ImageField:

def get_image_url(self): 
    """Method to return store image for admin panel""" 
    return '<img src="%s" height="150" width="150"/>' % self.storeImage.url 
get_image_url.allow_tags = True 

Я также изменил свое имя метода согласно python style guide.

+0

такой же результат проблема во время загрузки изображения .... –

0

Сначала код, чтобы получить путь проекта является неправильным:

PROJECT_DIR_PATH = path.dirname(path.dirname(__file__)) 

Вы должны получить абсолютного пути и вызов dirname дважды __file__ не имеет смысла:

PROJECT_DIR_PATH = path.dirname(path.normpath(path.abspath(__file__))) 

Во-вторых вам также необходимо установить MEDIA_URL как

MEDIA_URL = "/images/" 
Смежные вопросы