Login

All snippets

Snippet List

ReportBug() with tons of debug in mail

This basically takes the debug you get from setting debug=True, but instead, pipes it into an email and sends it over to you. I have extracted this out of our de framework, it should work, but some modifications may be necessary.

  • mail
  • report
  • bug
  • mail_admins
  • reportbug
Read More

ResizeImageField

ResizeImageField ================ (extension of RemovableImageField) ================================= by Wim Feijen, Go2People. What does it do? ---------------- ResizeImageField is a replacement for django's ImageField. It has two major benefits: 1. Creation of thumbnails and scaled images. 1. Extends the image upload form and adds a preview and a checkbox to remove the existing image. It's easy to use: - Replace ImageField by ResizeImageField - No further changes are necessary Requirements: ------------- Working installation of PIL, the Python Imaging Library Usage ----- - add resize_image to your app - add resize_filters.py to your templatetags - in settings.py, set a PHOTO_DIR, f.e. photos/original - in models.py, add: - from settings import PHOTO_DIR - from resize_image import ResizeImageField - photo = ResizeImageField(upload_to=PHOTO_DIR, blank=True) Scaled images will be stored in 'photos/scaled', thumbnails will be stored in 'photos/thumb'. Access your images from your template. Add:: {% load resize_filters %} {{ address.photo.url|thumb }} or:: {{ address.photo.url|scaled }} Defaults ------- - Scaled images are max. 200x200 pixels by default - Thumbnails are 50x50 pixels. Override the default behaviour in settings.py Scaling is done by PIL's thumbnail function, transparency is conserved. Credits ------ This code is an adaptation from python snippet 636 by tomZ: "Updated Filefield / ImageField with a delete checkbox"

  • image
  • thumbnail
  • resize
  • scale
  • delete
  • ImageField
  • ResizeImageField
  • removable
Read More
Author: wim
  • 5
  • 5

Exclude Apps When Testing

This allows you to exclude certain apps when doing standard tests (manage.py test) by default. You set the settings/local_settings variable EXCLUDE_APPS and it will exclude those apps (like django, registration, south... etc). This makes running tests much faster and you don't have to wait for a bunch of tests you don't care about (per say). You can override it by adding the app to the command line still. So if 'south' is in the excluded apps you can still run: 'python manage.py test south' and it will run the south tests. You will also need to tell django to use this as the test runner: TEST_RUNNER = 'testing.simple.AdvancedTestSuiteRunner'

  • testing
  • tests
  • exclude
Read More

SOAP web service with soaplib 0.9+

The popular [soaplib snippet](http://djangosnippets.org/snippets/979/) works only with older soaplib (0.8, for example). This snippet is modifed to work with newer soaplib: it was tested with 0.9.2-alpha3 and 1.0.0-beta4. I've tested suds python client and .NET client.

  • soap
  • soaplib
  • wsdl
Read More

Seamless Django and VirtualEnv integration

Automatically activates the virtualenv when running manage.py command. Just create requirements.pip file inside the root of django project and run ./manage.py update_ve in first time. Code checks requirements.pip and virtual env timestamps and require to recreate outdated environment.

  • pip
  • virtualenv
Read More

Django JSONP Decorator

This decorator function wraps a normal view function so that it can be read through a jsonp callback. Usage: @AllowJSONPCallback def my_view_function(request): return HttpResponse('this should be viewable through jsonp') It looks for a GET parameter called "callback", and if one exists, wraps the payload in a javascript function named per the value of callback. Using AllowJSONPCallback implies that the user must be logged in (and applies automatically the login_required decorator). If callback is passed and the user is logged out, "notLoggedIn" is returned instead of a normal redirect, which would be hard to interpret through jsonp. If the input does not appear to be json, wrap the input in quotes so as not to throw a javascript error upon receipt of the response.

  • jsonp
  • jsonp-decorator
Read More

Custom FileField with content type and size validation

Usage described in this blog post: [Django: FileField with ContentType and File Size Validation](http://nemesisdesign.net/blog/coding/django-filefield-content-type-size-validation/) Snippet inspired by: [Validate by file content type and size](http://djangosnippets.org/snippets/1303/)

  • forms
  • validation
  • upload
  • filefield
  • file
  • content-type
  • max_upload_size
Read More

Doing redirect without request

When you neeed to do redirect and request object is not available, you can do it with exception. Put exception handler somewhere request is available, for example to middleware or ModelAdmin. Raise exception, where request is not available.

  • http
  • request
  • redirect
  • reverse
  • httpresponse
Read More

Export Django data to datestamped tarball -- choose individual models for handy packaging and archiving

Just like it says -- set it up and run. Use it for server migrations, for project handoffs, in cron jobs, you name it. I have never had problems exporting models to individual fixtures in this way, and only one bout of trouble re-importing them (and that was, like, an impossible-triangle of OneToOneField dependencies anyway, and they were going from a sqlite file to a postgres schema that totally had inappropriate nullable columns in it). I find that the json files named for what they contain is helpful when and if manage.py does freak out during an import, as the output from `loaddata` command is so opaque it's autistic, basically. A trivial refactoring effort could make it into a management command -- it already makes use of the builtin `dumpdata` command class internally. However I did not feel like overthinking it enough to set it up in a repository (doubtlessly padded with unrelated 'utilities' and explanatory .rst files) and then writing a blog post to sell it to you. That is why you are reading this code here, instead of on GitHub. Don't get me wrong, GitHub is awesome, and like a consummate host... but not the way I love me some quick and dirty snippet code, these days. Whatever, you say lazy, I say productively relaxed, potato/potahto. Erm. In any case please do enjoy this model fixture-exporter. Yes.

  • django
  • python
  • json
  • export
  • data
  • script
  • command
  • archive
  • django1.1
  • backup
  • datestamp
  • tar
  • tarball
Read More

RSS feed with content:encoded elements

This creates an RSS feed that has "content:encoded" elements for each item in the feed. The "description" is best used for a brief summary of the entry, while the extra ["content:encoded"](http://purl.org/rss/1.0/modules/content#syntax2) element is designed for the entire contents of something. This is the code I'm using for a weblog app. The main features you'd need to copy to add "content:encoded" elements to your own feed are: * **ExtendedRSSFeed()** -- this is used to create a new kind of feed generator class that will know about these extra elements. * **feed_type = ExtendedRSSFeed** -- we tell the feed class which feed generator class to use. * **item_extra_kwargs()** -- we add the "content:encoded" element to each item. This populates the element by calling... * **item_content_encoded()** -- this prepares the actual content. The name doesn't have to be in this format, but it seemed sensible to follow convention. The body of my weblog Entries are split into two parts and here it makes sure we add both parts, both of which contain HTML (which the syndication classes will encode appropriately.

  • feed
  • rss
  • content
  • syndication
  • feeds
Read More

A RegexpField that clean the regex match using the desired format

I wanted a way to allow flexible phone number validation while making sure the saved data was uniform. ex. With: RegexFormatField(r'^\(?(?P<area>\d{3})\)?[-\s.]?(?P<local>\d{3})[-\s.]?(?P<subscriber>\d{4})$', format='%(area)s %(local)s-%(subscriber)s') input: (444) 444-4444 444 444-4444 444-444-4444 444.444.4444 4444444444 output: 444 444-4444

  • regex
  • format
  • field
Read More

Initially open collapsable fieldset class in admin

It's just an extension for the admin. Replace the collapse.js (collapse.min.js) and use it like this in the admin fieldset option: ´´**'classes': ['collapse', 'open']**´´. Without the 'open'-class, it will work as usual. *Needs possibly fixing for IE <= 8* because IE doesn't support the ´´:not´´ selector.

  • fieldset
  • collapse
  • collapsed
  • open
  • show
Read More

3110 snippets posted so far.