Login

Top-rated snippets

Snippet List

Dynamic thumbnail generator

This snippet creates thumbnails on-demand from a ImageField with any size using dynamics methods, like ``get_photo_80x80_url`` or ``get_photo_640x480_filename``, etc. It assumes you have an `ImageField` in your Model called `photo` and have this in your models.py: import re from os import path from PIL import Image GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$') `models.py` example: import re from os import path from PIL import Image from django.db import models GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$') class Photo(models.Model): photo = models.ImageField(upload_to='photos/%Y/%m/%d') <snippet here> Example usage: >>> photo = Photo(photo="/tmp/test.jpg") >>> photo.save() >>> photo.get_photo_80x80_url() u"http://media.example.net/photos/2008/02/26/test_80x80.jpg" >>> photo.get_photo_80x80_filename() u"/srv/media/photos/2008/02/26/test_80x80.jpg" >>> photo.get_photo_64x64_url() u"http://media.example.net/photos/2008/02/26/test_64x64.jpg" >>> photo.get_photo_64x64_filename() u"/srv/media/photos/2008/02/26/test_64x64.jpg"

  • image
  • thumbnail
  • model
  • imagefield
Read More

Form row filter

I love newforms. But sometimes using ``{{ form }}`` within a template doesn't give you enough flexibility. The other option, manually defining the markup for each field, is tedious, boring and error-prone. This is an example of how you can use a template filter to get the best of both worlds. Use it like this to render an entire form: ``{% for field in form %}`` {{ field|form_row }} ``{% endfor %}`` Or use it on a per-field basis: ``<fieldset>`` {{ form.first_name|form_row }} {{ form.last_name|form_row }} ``</fieldset>``

  • newforms
  • forms
  • templates
  • filters
Read More

Filter to resize a ImageField on demand

A filter to resize a ImageField on demand, a use case could be: ` <img src="object.get_image_url" alt="original image"> <img src="object.image|thumbnail" alt="image resized to default 200x200 format"> <img src="object.image|thumbnail:"200x300" alt="image resized to 200x300"> ` The filter is applied to a image field (not the image url get from *get_image_url* method of the model), supposing the image filename is "image.jpg", it checks if there is a file called "image_200x200.jpg" or "image_200x300.jpg" on the second case, if the file isn't there, it resizes the original image, finally it returns the proper url to the resized image. There is a **TODO**: the filter isn't checking if the original filename is newer than the cached resized image, it should check it and resize the image again in this case.

  • filter
  • models
  • thumbnail
  • resize
  • imagefield
Read More

{% with %} template tag

Add a value to the context (inside of this block) for easy access. Provides a way to stay DRYer in your templates. **NOTE:** This tag is now in Django core, so if you have Django >0.96 (or SVN) then you do NOT need this.

  • template
  • template-tag
  • encapsulation
Read More

PyIf Template Tag (Conditional Tag)

Cheers to limodou for getting me thinking about this. The only problem with his implementation is that it doesn't support Django's "." syntax for accessing array/dict elements. In the Django style of allowing simple syntax for designers while allowing for greater flexibility, and less template duplication for conditionals that were previously impossible to represent in templates, I modified Django's built-in If tag. This is an adaptation/enhancement to Django's built in IfNode {% if ... %} that combines if ifequal ifnotequal into one and then adds even more. This Supports 1. ==, != 2. not .... 3. v in (1,"y",z) 4. <=, <, >=, > 5. nesting (True and (False or (True or False))) How to use it: {% pyif i == 1 or (5 >= i and i != 7) and user.first_name in ('John', 'Jacob') %} 'Tis true. {% else %} 'Tis false. {% endif %} I hope you like it.

  • template
  • tag
  • templatetag
  • if
  • conditional
  • ifequal
  • ifnotequal
Read More

mask_email filter

Mask an email address by removing most of the first portion and replacing it with "..." For example. If you have a variable in your template context named `email_address `, and its value is "[email protected]" {{ email_address|mask_email }} will render as: [email protected] If the part preceding @domain.com is shorter than 5 characters, only the first letter will be used, followed by "...". So if we have "[email protected]" {{ email_address|mask_email }} will render as: [email protected]

  • filters
  • email
Read More

reCAPTCHA integration

Integrating [reCAPTCHA](http://recaptcha.net/) with Django. **Warning**: although *remoteip* is used as optional parameter in this snippet, it is likely to become mandatory in the future. Please see [the comment by Jim Garrison](http://www.marcofucci.com/tumblelog/26/jul/2009/integrating-recaptcha-with-django/#comment-262) for more detail. Generic version of [this snippet](http://www.djangosnippets.org/snippets/433/). 1. Register on [reCAPTCHA](http://recaptcha.net/) to get your public/private key pair 2. Add your keys in settings.py 3. Add [recaptcha-client](http://pypi.python.org/pypi/recaptcha-client) to your project 4. Put ReCaptchaField and ReCaptcha widget somewhere (I've used a generic app `marcofucci_utils`) 5. Configure your form More information on my website [marcofucci.com](http://www.marcofucci.com/tumblelog/26/jul/2009/integrating-recaptcha-with-django/).

  • captcha
  • recaptcha
Read More

Readonly admin fields

Put this code and import it where you define your ModelAdmin-classes. # typical admin.py file: from django.contrib import admin from foo.bar import ReadOnlyAdminFields class MyModelAdmin(ReadOnlyAdminFields, admin.ModelAdmin): readonly = ('field1', 'field2',)

  • django
  • admin
  • field
  • readonly
Read More

Digg-like paginator, updated

This is an updated version of http://www.djangosnippets.org/snippets/628/ now working with Django's new Paginator class, instead of the deprecated ObjectPaginator. See: http://blog.elsdoerfer.name/2008/05/26/diggpaginator-update/

  • pagination
  • paginator
  • digg
Read More

Unique Slugify

Automatically create a unique slug for a model. Note that you *don't* need to do `obj.slug = ...` since this method updates the instance's slug field directly. All you usually need is: `unique_slugify(obj, obj.title)` A frequent usage pattern is to override the `save` method of a model and call `unique_slugify` before the `super(...).save()` call.

  • slug
Read More

"for" template tag with support for "else" if array is empty

This is a customized version of the default `for` template tag which takes an optional `{% else %}` clause that will be displayed if the given array is empty. from django.template import * >>> t1 = Template(""" {% load mytags %} {% for athlete in athlete_list %} {{ athlete }} {% else %} No athlete in list! {% endfor %} """) >>> c1 = Context( {'athlete_list': ['me', 'myself', 'I'] }) >>> t1.render(c1) u'me myself I ' >>> c2 = Context({}) >>> t1.render(c2) u'No athlete in list!' If you want to automatically override the builtin `for` template-tag add it to the builtins: from django.template import add_to_builtins add_to_builtins('python.path.to.mytags')

  • template
  • tags
  • template-tag
  • templatetags
  • forloop
Read More

Send large files through Django, and how to generate Zip files

This snippet demonstrates how you can send a file (or file-like object) through Django without having to load the whole thing into memory. The FileWrapper will turn the file-like object into an iterator for chunks of 8KB. This is a full working example. Start a new app, save this snippet as views.py, and add the views to your URLconf. The send_file view will serve the source code of this file as a plaintext document, and the send_zipfile view will generate a Zip file with 10 copies of it. Use this solution for dynamic content only, or if you need password protection with Django's user accounts. Remember that you should serve static files directly through your web server, not through Django: http://www.djangoproject.com/documentation/modpython/#serving-media-files

  • sendfile
  • zipfile
  • tempfile
  • temporaryfile
  • filewrapper
Read More

Google Geocode Lookup

Makes a call to Google's geocoder and returns the latitude and longitude as a string or returns an empty string. Called by the save method to save the lat and long to the db to be used when rendering maps on the frontend. Reduces the number of calls to geocoder by calling only when saving, not on every viewing of the object. Be sure to import *urllib* and the project's *settings*, and to define GOOGLE_API_KEY in settings.py. **Example:** def save(self): location = "%s+%s+%s+%s" % (self.address, self.city, self.state, self.zip_code) self.lat_long = get_lat_long(location) if not self.lat_long: location = "%s+%s+%s" % (self.city, self.state, self.zip_code) self.lat_long = get_lat_long(location) super(Foo, self).save()

  • google-maps
  • geocode
  • google-api
  • latitude
  • longitude
Read More

SQL Printing Middleware

Just put it in your python path and add it into MIDDLEWARE_CLASSES. I know that there are a couple of snippets on this site that do something similar to this, but none of them quite suited me. I wanted something that would indent and space the SQL so that I could differentiate it from the other output from the development server. Also, I wanted something that would output total query execution time, which my solution does. I just hope that it's useful for someone else, too! UPDATE: Now this should no longer get upset when running it on windows.

  • sql
  • middleware
  • profile
  • debug
  • help
  • console
  • printing
  • speed
Read More

3110 snippets posted so far.