【发布时间】:2014-07-05 15:19:57
【问题描述】:
我是 django 的新手。我有一个项目,用户可以在其中下载各种图像。我想跟踪下载的图像。这就是为什么我想将下载的图像文件存储在临时文件中。我已经创建了一个模型这个,下面给出..
class Photo(models.Model):
name = models.CharField(max_length = 100)
photo = models.ImageField(upload_to = 'downloaded', blank=False,null=True)
description = models.CharField(max_length = 80 , blank = False , null = True)
user = models.ForeignKey(User)
def __unicode__(self):
return '%s %s %s' %(self.description,self.name)
def _get_image_url(self):
return self.photo
和views.py
def download(request,image_id):
filename = get_object_or_404(Photo,pk = image_id)
filepath = filename.photo.url
contributor = filename.user
wrapper = FileWrapper(open(filepath,'rb',))
content_type = mimetypes.guess_type(filepath)[0]
response = HttpResponse(wrapper, mimetype='content_type')
response['Content-Disposition'] = "attachment; filename=%s" % filepath
if response and not filename.user==request.user:
purchased_image=PhotoDownload(name=filename.name,dowloaded_photo=filepath,user = request.user)
purchased_image.save()
return response
根据给定的模型和视图,每当我下载任何图像时,都应该在 media 目录中创建一个 download 文件夹,不是吗?但是在下载任何图像后,没有在媒体目录中创建 download forlder,而是图像存储在数据库中,带有一个 url,就像这样......
http://med.finder-lbs.com/admin/photo/photodownload/2/media/media/photos/2_4.jpg
如果你仔细查看 url,你会发现图像存储在 /media/media/photos 应该存储在 media/photos 的位置,为什么会这样?我错过了什么还是有其他方法可以将下载的文件存储在临时文件夹中?我的其他照片,例如 上传的照片 存储在临时文件中,但下载的照片会导致问题。为了更方便,这里是 setting.py
import os
SETTINGS_DIR = os.path.dirname(__file__)
PROJECT_PATH = os.path.join(SETTINGS_DIR,os.pardir)
PROJECT_PATH = os.path.abspath(PROJECT_PATH)
# Django settings for shutterstock project.
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
TEMPLATE_CONTEXT_PROCESSORS += (
'django.core.context_processors.request',
)
DEBUG = True
TEMPLATE_DEBUG = DEBUG
#for Template path
TEMPLATE_PATH = os.path.join(PROJECT_PATH,'templates')
# Absolute filesystem path to the directory that will hold user-uploaded files.
# Example: "/var/www/example.com/media/"
MEDIA_ROOT = os.path.join(PROJECT_PATH, 'media')
MEDIA_URL = '/media/' #GORKY >> This was media/
# 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: "/var/www/example.com/static/"
STATIC_ROOT = ''
STATIC_PATH = os.path.join(PROJECT_PATH,'static')
#STATIC_PATH = os.path.abspath(os.path.join(PROJECT_PATH, 'static'))
# URL prefix for static files.
# Example: "http://example.com/static/", "http://static.example.com/"
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.
STATIC_PATH,
)
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'stock', # Or path to database file if using sqlite3.
# The following settings are not used with sqlite3:
'USER': '',
'PASSWORD': '',
'HOST': '', # Empty for localhost through domain sockets or '127.0.0.1' for localhost through TCP.
'PORT': '', # Set to empty string for default.
}
}
ALLOWED_HOSTS = []
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
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/"
# URL that handles the media served from MEDIA_ROOT. Make sure to use a
# trailing slash.
# Examples: "http://example.com/media/", "http://media.example.com/"
# 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: "/var/www/example.com/static/"
# URL prefix for static files.
# Additional locations of static files
# 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 = '3zf@!cs!z(dsf3&6p93jrc6qz)-22n@uyps!5p*wkr3pxemy9e'
# 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',
)
TEMPLATE_DIRS = (TEMPLATE_PATH,)
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 = 'shutterstock.urls'
# Python dotted path to the WSGI application used by Django's runserver.
WSGI_APPLICATION = 'shutterstock.wsgi.application'
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfiles',
# Uncomment the next line to enable the admin:
'django.contrib.admin',
# Uncomment the next line to enable admin documentation:
# 'django.contrib.admindocs',
'photo',
'userena',
'guardian',
'easy_thumbnails',
'accounts',
'cloudinary',
'paypal.standard.ipn',
'myprofile',
'watermarker',
'mail',
'stored_messages',
'rest_framework',
'endless_pagination',
'home',
'easy_thumbnails',
)
MESSAGE_STORAGE = 'stored_messages.storage.PersistentStorage'
WATERMARKING_QUALITY = 85
WATERMARK_OBSCURE_ORIGINAL = False
WATERMARK_OBSCURE_ORIGINAL = False
AUTHENTICATION_BACKENDS = (
'userena.backends.UserenaAuthenticationBackend',
'guardian.backends.ObjectPermissionBackend',
'django.contrib.auth.backends.ModelBackend',
)
ANONYMOUS_USER_ID = -1
SESSION_SERIALIZER = 'django.contrib.sessions.serializers.JSONSerializer'
AUTH_PROFILE_MODULE = 'accounts.MyProfile'
LOGIN_REDIRECT_URL = '/accounts/%(username)s/'
LOGIN_URL = '/accounts/signin/'
LOGOUT_URL = '/accounts/signout/'
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,
},
}
}
THUMBNAIL_ALIASES = {
'': {
'mini': {'size': (50, 50), 'crop': True},
'small': {'size': (100, 100), 'crop': True},
'regular': {'size': (200, 200), 'crop': True},
'large': {'size': (500, 500), 'crop': True},
'xl': {'size': (800, 800), 'crop': True},
'a4': {'size': (800, 600), 'crop': True},
},
}
那么你有什么想法吗?
【问题讨论】:
-
将下载的图像保存到临时文件夹有什么意义?您在响应中将图像发送给用户。您已经拥有图像存储在服务器上,而您只是在浪费磁盘空间。此处是否要求能够跟踪用户何时下载图像?
-
我只是忘了说主要目的,主要目的是,对下载的图像进行历史记录并显示给用户。