通过Django管理面板上传图片无法正常工作

时间:2013-08-22 12:35:50

标签: python 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     
)

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

项目目录结构:

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

有人可以帮助我....

2 个答案:

答案 0 :(得分:0)

MEDIA_URL url ,而不是文件路径。你需要:

MEDIA_URL = "images/"

您还需要更改upload_to字段,否则您的图片会进入/flipdiscountApp/images/images/

您还应该使用ImageField的{​​{3}}:

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

我还根据url property更改了您的方法名称。

答案 1 :(得分: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/"