Login

All snippets written in Python

2956 snippets

Snippet List

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

Making templatetags global to all templates

I found myself putting `{%load ... %}` in every template that I was writing, so DRY .. I created an app called 'globaltags' and in its `__init__.py`, I just pre-load the tags that I use frequently. The [pyif](http://www.djangosnippets.org/snippets/130/) and [expr](http://www.djangosnippets.org/snippets/9/) tags are excellent tags, and I highly recommend them for getting the most out of django's template language. The [dbinfo](http://www.djangosnippets.org/snippets/159/) snippet is something that I came up with to easily output SQL debugging information.

  • tag
Read More

MintCache

MintCache is a caching engine for django that allows you to get by with stale data while you freshen your breath, so to speak. The purpose of this caching scheme is to avoid the dog-pile effect. Dog-piling is what normally happens when your data for the cache takes more time to generate than your server is answering requests per second. In other words if your data takes 5 seconds to generate and you are serving 10 requests per second, then when the data expires the normal cache schemes will spawn 50 attempts a regenerating the data before the first request completes. The increased load from the 49 redundant processes may further increase the time it takes to generate the data. If this happens then you are well on your way into a death spiral MintCache works to prevent this scenario by using memcached to to keep track of not just an expiration date, but also a stale date The first client to request data past the stale date is asked to refresh the data, while subsequent requests are given the stale but not-yet-expired data as if it were fresh, with the undertanding that it will get refreshed in a 'reasonable' amount of time by that initia request I don't think django has a mechanism for registering alternative cache engines, or if it does I jumped past it somehow. Here's an excerpt from my cache.py where I'v just added it alongside the existing code. You'll have to hook it in yourself for the time being. ;-) More discussion [here](http://www.hackermojo.com/mt-static/archives/2007/03/django-mint-cache.html).

  • cache
  • mint
  • memcached
Read More

Find all links in a value and display them separatley

This is a simple filter I use to display a list of links from a blog entry off in the sidebar ([example](http://www2.jeffcroft.com/blog/2007/feb/25/two-new-django-sites-both-source-available/)). Requires beautifulsoup. Originally by [Nathan Borror](http://playgroundblues.com), tweaked slightly by me.

  • template
  • filter
  • beautifulsoup
Read More

Pygments Rendering Template Filter

Finds all ``<code></code>`` blocks in a text block and replaces it with pygments-highlighted html semantics. It tries to guess the format of the input, and it falls back to Python highlighting if it can't decide. This is useful for highlighting code snippets on a blog, for instance.

  • template
  • filter
  • pygments
  • highlighting
  • code
Read More