简体   繁体   中英

django Downloaded image file not storing in a temp file

I am new in django.I have a project where user can download various images.I want to keep track on downloaded image.Thats why i want to store the downloaded image file in a temp file.i have create a model for this,which is given below..

 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

and 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

according to the given model and view , whenever i download any image,it should create a download folder in the media directory,isn't it? but after download of any image,no download forlder is creating in the media directory, but the image is storing in the database,with a url ,which is something like that ...

http://med.finder-lbs.com/admin/photo/photodownload/2/media/media/photos/2_4.jpg

if you make a close look at the url,you will find that the image is storing /media/media/photos where it should be store in media/photos , why it's happening? am i missing anything or are there another way to store downloaded file in temp folder? My other photos,such as uploaded photos are storing in a temp file,but the downloaded photos are causing problem.For better convenience ,here is 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},
       },
   }

So do you have any idea?

The upload_to attribute of Image tells django where to store files when they are being uploaded, not downloaded. It makes not sense to store files when you download them... you don't want your disk to be populated by copies of the same file everytime it is download, don't you?

If you want to maintain a log of requests you can store the id, or the filename of the image in your database. You can achieve this with a new model containing a timestamp and some log information.

Track downloads

To keep a track of image downloads, you want something like this:

models.py:

from django.contrib.auth.models import User

class Photo(models.Model):
    photo = models.ImageField(upload_to = 'downloaded', blank=False,null=True)
    ...

class Download(models.Model):
    photo = models.ForeignKey(Photo)
    user = models.ForeignKey(User, related_name='downloads')
    downloaded = models.DateTimeField(auto_now_add=True)
    # any other fields you want to store

views.py:

def download(request, photo_id):
    photo = get_object_or_404(Photo, pk=photo_id)
    download = Download(photo=photo, user=request.user)
    download.save()
    # serve file

This creates a record in the database for every file download, showing the file downloaded, the user who downloaded it, and the date/time of the download. If you don't have logged in users, you could store other things, like the client IP address for example.

Display download list

To show a list of download for the current user, you could then use a view and template like this:

views.py:

def my_downloads(request):
    downloads = request.user.downloads.all()
    return render(request, "my_downloads.html", {'downloads': downloads})

my_downloads.html:

...
<p>You've downloaded the following images:</p>
<ul>
    {% for download in downloads %}
        <li>{{ download.photo.photo.name }}</li>
    {% endfor %}
</ul>
...

Further help

With regard to how you are currently doing the # serve file bit. You probably don't what to serve the file directly in the view. You could simply redirect the request to the url of the file:

from django.shortcuts import redirect

def download(request, photo_id):
    ...
    return redirect(photo.photo.url)

This means that Django doesn't have to do the work of actually sending file.

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