Login

Top-rated snippets

Snippet List

Automatically expose soaplib methods in WSDL

This snippet is a replacement views.py for [SOAP views with on-demand WSDL generation](http://www.djangosnippets.org/snippets/979/) It iterates over your installed apps looking for web_service.py in each one, any methods decorated with @soapmethod within web_service.py will automatically be imported into the local namespace making them visible in the WSDL. It will blindly override local objects of the same name so it's not very safe (could do with some more error checks) but it works very well.

  • soap
  • soaplib
  • wsdl
  • web-services
Read More

Temporary admin messages (MOTD)

This small app can display messages to users after they login and before they get to the normal landing page. This can be useful for displaying maintenance notices, information on new features, or a one-day-sale on shoes. To redirect to the MOTD view after login, change: `<input type="hidden" name="next" value="{{ next }}" />` to: `<input type="hidden" name="next" value="{% url django_motd.views.motd %}?next={{ next }}" />` in your login.html template.

  • admin
  • login
  • message
  • motd
Read More

Unit Tests That Write Fixtures

This is a skeleton framework of a unittest for an app which will write out a fixture of the test database once the test has been done. I run this once for all apps, but you can limit which apps get serialized by modifying the self.apps value from get_apps (all apps) to a list of only certain apps. This script by default assumes that you have a SVN_DIR setting which points to the current working subversion directory, with a subdirectory of fixtures where it places `tests.json` upon completion. You may change this location as well. After running `python manage test` you can run `python manage loaddata fixtures/tests.json` to load in to the real database all of the test database fixtures. Feel free to edit at will, let me know of any changes that are helpful, and dont forget to fill in the `...`s

  • json
  • unittest
  • fixture
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

Fake File Uploads

In-browser testing frameworks (I'm using [Windmill](http://www.getwindmill.com/)) have trouble testing file uploads because javascript's security policy prevents them from setting the value of file input fields. Instead the tests must issue some sort of "fake" file upload request, but implementing this on an ad-hoc basis quickly gets ugly. This middleware is designed to support fake file uploads as transparently and as thoroughly as possible. For example, it is careful to properly trigger any file upload handlers so that things like upload progress reporting will work correctly. It can also simulate a slow file upload by sleeping between reads from the file. From the client-side point of view, each input field of type "file" has a similarly-named hidden field automatically prepended. Test scripts can simply set the value of this hidden field to trigger a fake upload, rather than having to set the value of the file input field itself.

  • upload
  • testing
  • file
Read More
Author: rfk
  • 1
  • 3

JSONable model base

This is a basic stub for a model that you can use to easily add customizable JSON serialization to your models. Make your model inherit from JsonableModel, and then define the models/yourmodel.json template with whatever information from the model that you want to make available.

  • model
  • json
  • inherit
Read More

Filter; Capitalise Sentences (capsentence)

Given a string, it first lowercases it, then uppercases the first letter of each sentence. Helpful when dealing with awfully formatted entirely UPPERCASE XML product data feeds.

  • capitalize
  • capitalise
  • sentence
  • sentences
  • capitalises
  • capitalizes
  • prettifies
  • sentance
Read More
Author: djm
  • 1
  • 0

decorator to synchronize method at class / module level

This decorator allows you to wrap class methods or module functions and synchronize access to them. It maintains a dict of locks with a key for each unique name of combined module name and method name. (Implementing class name is lost in decorator? Otherwise it would have class name too if available.) Effectively it functions as a class level method synchronizer, with the lock handling completely hidden from the wrapped function.

  • decorator
  • method
  • class
  • synchronize
Read More

CountryField (UN Country List, 3 Char Codes)

**Adapted from** [CountryField](http://www.djangosnippets.org/snippets/494/) - **Initial thanks to marinho** Uses the UN country list listed in the source - this provides the 3 character ISO country code. Ordered by display value and not country code. Just place anywhere you like and import CountryField to use. `country = CountryField(verbose_name="Country", help_text="The registrant's country of residence.")`

  • forms
  • form
  • field
  • list
  • country
  • countries
  • custom
  • custom-field
  • countryfield
  • countrys
Read More
Author: djm
  • 1
  • 1

Null Field Admin Filter

This patch adds a new admin Filter, for Filtering nullable fields. It adds 3 possible choices: 'All' (no filter), 'Null' (it applies field__isnull=True filter), and 'With Value' (it filters null values). This patch is interesting when you have a Integer or String fields and you want to filter wether a value is set or not. In other case, it would show too many filtering options. Remember this is a patch and you must modify a django file in `django/contrib/admin/filterspecs.py`

  • filter
  • admin
  • null
Read More

Unsharp Mask with PIL and PythonMagick

**A Magick PIL** I used to do my image conversions with ImageMagick and system calls back in my PHP days. With Django PIL is the obvious choice for most image stuff, but frustrated by the lack of a proper unsharp mask function for PIL I found some code in the bits and pieces of documentation for PythonMagick. (yes I know, Kevin Cabazon wrote PIL_usm, but I could not get it to work, probably due to my inexperience. Anyway, this code makes it easy to convert back and forth from PIL to PythonMagick (maybe not such a good idea on a memory tight high loaded production server, but no problem on my private server (Pentium-M @ 1.8 Ghz with 1 GB Mem.) **usage:** usm takes a PIL image object. Radius and sigma is in pixels, amount 1 compares to 100% in photoshop, threshold 0.004 ~ (1/256) compares to 1 in photoshop: I'm using r=1,s=0.5,a=0.8,t=0.016 for roughly 800x600 images created from 3000x2000 (6MP) images. Experiment for your own preferences.

  • image
  • pil
  • sharpen
  • thumbnails
  • pythonmagick
  • usm
Read More

ModelForm ExtJS JSON Encoder

from http://www.djangosnippets.org/snippets/792/ from utils.extjs import ExtJSONEncoder from django.utils.safestring import mark_safe class TestForm(forms.ModelForm): class Meta: model = TestModel def as_ext(self): return mark_safe(simplejson.dumps(self,cls=ExtJSONEncoder))

  • json
  • modelform
  • extjs
Read More

Update Related Object Fields

Some times I want to change the `owner` of an object to another user - problem is the object often has a lot of other objects pointing to them - I also want to update those fields. This is a generic snippet for doing just that! For instance: change_owner(obj, new_owner_id): return update_related_field(obj, new_owner_id, field="user")

  • related
  • update
Read More

Facebook Connect Middleware

This middleware will look for the cookies set when a Facebook Connect user authenticates to your site, read those cookies, determine if the logged in user is your Facebook friend and then log that user into your Django-powered site. If you don't need the bit about friend verification, it should be trivial to strip out. There are a couple of other things that are needed to get FB Connect working with your site, and you can find a more detailed entry [here (http://nyquistrate.com/django/facebook-connect/)](http://nyquistrate.com/django/facebook-connect/).

  • middleware
  • facebook
  • facebook-connect
Read More

3110 snippets posted so far.