Login

Tag "files"

Snippet List

Unique naming for file uploads

This snippit can be used to generate unique file names for uploads. `upload_to` allows a callable, but only provides two arguments: `instance` and `filename`. In order to prevent dumping all of the files for a model into one directory, this utilizes the `partial` decorator from `functools`, which essentially allows adding an extra argument to the function. The returned path will be of the form: `[model name]/[field_name]/[random hash].[filename extension]`

  • files
  • path
  • naming
  • uploads
Read More

Fix for GZipMiddleware when serving files or streaming or using iterators

A simple replacement for Django's default GZipMiddleware which breaks when trying to serve files or pass any kind of iterators to the HttpResponse object. Simply replace GZipMiddleware with the provided middleware and set response.dontgzip = True when returning the response, and it will then be ignored by the middleware.

  • files
  • gzip
  • streaming
  • gzipmiddleware
Read More

Load static media from secure (SSL) static server (Context Processor)

If you request static files such as images, javascript or css using http rather than https, the browser will complain that your site is not secure. This simple context processor will replace http:// with https:// in your MEDIA_URL if your static files are being included from an https page. In your settings.py just replace 'django.core.context_processors.media' with your new context processor.

  • files
  • ssl
  • context
  • static
  • processor
  • secure
  • content
  • media_url
Read More

Database file storage

Class DatabaseStorage can be used with either FileField or ImageField. It can be used to map filenames to database blobs: so you have to use it with a **special additional table created manually**. The table should contain: *a pk-column for filenames (I think it's better to use the same type that FileField uses: nvarchar(100)) *a blob column (image type for example) *a size column (bigint type). You can't just create blob column in the same table, where you defined FileField, since there is no way to find required row in the save() method. Also size field is required to obtain better perfomance (see size() method). So you can use it with different FileFields and even with different "upload_to" variables used. Thus it implements a kind of root filesystem, where you can define dirs using "upload_to" with FileField and store any files in these dirs. Beware saving file with the same "virtual path" overwrites old file. It uses either settings.DB_FILES_URL or constructor param 'base_url' (@see __init__()) to create urls to files. Base url should be mapped to view that provides access to files (see example in the class doc-string). To store files in the same table, where FileField is defined you have to define your own field and provide extra argument (e.g. pk) to save(). Raw sql is used for all operations. In constractor or in DB_FILES of settings.py () you should specify a dictionary with db_table, fname_column, blob_column, size_column and 'base_url'. For example I just put to the settings.py the following line: DB_FILES = {'db_table': 'FILES', 'fname_column': 'FILE_NAME', 'blob_column': 'BLOB', 'size_column': 'SIZE', 'base_url': 'http://localhost/dbfiles/' }" And use it with ImageField as following: player_photo = models.ImageField(upload_to="player_photos", storage = DatabaseStorage() ) DatabaseStorage class uses your settings.py file to perform custom connection to your database. The reason to use custom connection: http://code.djangoproject.com/ticket/5135 Connection string looks like "cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=testdb;UID=me;PWD=pass')" It's based on pyodbc module, so can be used with any database supported by pyodbc. I've tested it with MS Sql Express 2005. Note: It returns special path, which should be mapped to special view, which returns requested file: **View and usage Example:** def image_view(request, filename): import os from django.http import HttpResponse from django.conf import settings from django.utils._os import safe_join from filestorage import DatabaseStorage from django.core.exceptions import ObjectDoesNotExist storage = DatabaseStorage() try: image_file = storage.open(filename, 'rb') file_content = image_file.read() except: filename = 'no_image.gif' path = safe_join(os.path.abspath(settings.MEDIA_ROOT), filename) if not os.path.exists(path): raise ObjectDoesNotExist no_image = open(path, 'rb') file_content = no_image.read() response = HttpResponse(file_content, mimetype="image/jpeg") response['Content-Disposition'] = 'inline; filename=%s'%filename return response **Warning:** *If filename exist, blob will be overwritten, to change this remove get_available_name(self, name), so Storage.get_available_name(self, name) will be used to generate new filename.* For more information see docstrings in the code. Please, drop me a line if you've found a mistake or have a suggestion :)

  • files
  • database
  • storage
  • filestorage
Read More

Overwrite File Storage System

This is a simple implementation overwrite of the FileSystemStorage. It removes the addition of an '_' to the filename if the file already exists in the storage system. I needed a model in the admin area to act exactly like a file system (overwriting the file if it already exists).

  • files
  • storage
Read More

divShareApi

A python module for integration with http://www.divshare.com/integrate/api.

  • files
  • api
  • media
  • photos
  • divshare
  • video
Read More

Upload a zip file with newforms

This is a minor modification to [Upload a file using newforms](http://www.djangosnippets.org/snippets/95/) as posted by [mboersma](http://www.djangosnippets.org/snippets/95/). I altered the ZipUploadForm by removing lines 33 - 34: if 'zip_file' in self.clean_data: zip_file = self.clean_data['zip_file'] and adding a return statement to clean_zipfile, which returns the validated zip file. I also added the line: zip_file.clean = clean_zipfile so that when the full_clean() in called on the form, clean_zipfile will automatically run. All other code (the view & template) remain the same. ** Disclaimer ** I'm not *that* familiar with newforms, so please forgive me if some the explanation as to why this works is incorrect ;) Who knows, maybe the first guy had it right.

  • newforms
  • files
  • zip-files
  • upload
Read More

send_file and send_data

Simple functions for downloading files - send_data sends the data directly, send_file as attachment. May need optimizing for large files.

  • files
  • download
Read More

Upload a file using newforms

Django's transition from oldforms to newforms is nearing. If you're using recent trunk source code from Django's subversion repository, you should start using newforms. But there are still some rough edges as of today. File uploading seems to be one of them. (Adrian and other Django folks are well aware of this. Please don't bother them by asking "Are we there yet?") The Django mailing lists and Google searching didn't turn up any best practices for this area of newforms, so I muddled through it and here's the result. I omit the urls.py code necessary to hook up the zip_upload method to a URL, but otherwise this should be complete. And if I haven't loaded this with enough caveats...please be aware this code may be obsoleted soon.

  • django
  • newforms
  • files
  • forms
Read More

Keep settings.py in version control safely

Here is a trivial way to keep your Django project in shared version control or in a public repository without exposing settings that could have security implications, and without needing to modify settings.py for your local test or production environments on checkout. This is also a way to separate development settings from production settings, or to deploy the same code on multiple servers while only changing one site-specific "dotfile."

  • files
  • configuration
  • settings
  • development
  • debug
Read More

Serving null files

Sometimes you have to serve null files. This quick hacky generic view lets you do that. The best example of that is robots.txt, I want my robots.txt to always be empty, at least for now. The other example would be favicon.ico, but that's more often used to actually fill a purpose.

  • null
  • files
  • views
Read More

12 snippets posted so far.