Login

All snippets written in Python

Snippet List

Custom Django manager that excludes subclasses

When you're using Django model inheritance, sometimes you want to be able to get objects of the base class that aren't instances of any of the subclasses. You might expect the obvious way of doing this, `SuperModel.objects.filter(submodel__isnull=True)`, to work, but unfortunately it doesn't. (Neither does `SuperModel.objects.filter(submodel__supermodel_ptr=None)`, or any other convoluted way I could think of doing it.) Here's a nicer approach for doing this. [The blog entry is here.](http://sciyoshi.com/blog/2008/aug/07/custom-django-manager-excludes-subclasses/)

  • managers
  • models
  • model
  • subclass
  • manager
  • inheritance
  • subclasses
Read More

CustomImageField for Django 1.0 alpha

The venerable CustomImageField, invented by [Scott Barnham](http://scottbarnham.com/blog/2007/07/31/uploading-images-to-a-dynamic-path-with-django/) and rejiggered for newforms-admin by [jamstooks](http://pandemoniumillusion.wordpress.com/2008/08/06/django-imagefield-and-filefield-dynamic-upload-path-in-newforms-admin/#comments). This here is a stab at a [post-Signals-refactor](http://code.djangoproject.com/wiki/BackwardsIncompatibleChanges#Signalrefactoring) version. Seems to do 'er. Note: This should be pointless once [fs-refactor](http://code.djangoproject.com/ticket/5361) lands.

  • models
  • fields
  • imagefield
  • newforms-admin
  • signals
Read More

djangopath: conveniently set sys.path and DJANGO_SETTINGS_MODULE

In the past, whenever I had a script that I wanted to properly configure the settings for, I would use something like the following idiom at the top of the script: import sys, os; dirname = os.path.dirname # sys.path.insert(0, dirname(dirname(__file__))) sys.path.insert(0, dirname(__file__)) os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp.settings' Notice that this is a relative setting to `__file__` variable in the script. The djangopath function is an attempt to do away with the above such that I can now write the following: from lib import djangopath; djangopath(up=2, settings='myapp.settings') This seems to work for me, but it assumes that you are packaging your script inside your projects/apps. If they are elsewhere then you may need to resort to another method (e.g. absolute paths, etc.) AK

  • settings
  • path
Read More

versioned_media templatetag

Best practice based on [YSlow recommendations](http://developer.yahoo.com/yslow/), add the following to your Apache config for your media directory. <Directory /home/.../site_media/> ... FileETag None ExpiresActive on ExpiresDefault "access plus 10 years" AddOutputFilterByType DEFLATE text/css application/x-javascript </Directory` Make sure to enable mod_deflate and mod_expires.

  • templatetag
  • css
  • media
  • js
  • versioned_media
Read More

RefreshSessionMiddleware

This middleware refreshes the session before it expires to avoid dropping the session of an active (but read-only) user. By default it refreshes the session after half the expiry time has elapsed. (This middleware does nothing for browser-length sessions.)

  • sessions
  • refresh
Read More

Git recent commits template tag

Requires [GitPython](http://gitorious.org/projects/git-python). Grabs the most recent commits to a Git repository, as defined in `settings.py`. Inspired by [Simon Willison](http://simonwillison.net)'s [about page](http://simonwillison.net/about/). **Example:** {% get_recent_commits 10 as commits %} <ul> {% for commit in commits reversed %} <li>{{ commit.commited_date }} - {{ commit.message }}</li> {% endfor %} </ul>

  • templatetag
  • git
Read More

Serve static media files from app/media subdirectory

This view will serve media files from all media subdirectories of apps in your INSTALLED_APPS setting. Save the view as media.py in your django site folder and add to urls.py: if settings.DEBUG: urlpatterns += patterns('', (r'^media/(?P<appname>\w+)/(?P<path>.+)$', 'devel_site.media.serve_apps') )` Now suppose your installed apps setting looks like: INSTALLED_APPS = ('org.myself.myapp', ...) Then a request to http://localhost/media/myapp/directory/file.css will serve the file org/myself/myapp/media/directory/file.css.

  • media
  • static-media
Read More

Render specific blocks from templates (useful for AJAX, alternative)

Special thanks to the author of snippet 769 who provided most of the code for this snippet. Major differences: 1.Simpler/better handling of "extends" block tag 2.Searches If/Else blocks 3.Less code 4.Allow list of templates to be passed which is closer to the behavior of render_to_response

  • template
  • block
  • templates
  • render
  • context
  • blocks
Read More

very simplistic url cache flushing

This is an (overly simple) example of how to manually delete something from the cache. Usage is simply `delete_url_cache('/some_view/')` This most likely doesn't work when using Vary headers but does seem to work fine for the most general case of simply needing to programmatically flush the cache after certain actions.

  • cache
Read More
Author: jpt
  • 1
  • 3

Replace Paragraph Tags for Flash

This template tag does two things needed to display content from something like a TextField wrapped with TinyMCE in Flash's htmlText component: 1. Replace `<p>` tags with `<br />` 2. Strip all occurances of `\n`

  • template
  • tag
Read More

sorl.thumbnail processor: white background

If you want to resize transparent PNGs with the `{% thumbnail %}` templatetag, they'll sometimes get an ugly black background that looks even more ugly on a white background. This processor puts the image on a white background. You can simply change the background color by replacing `white` with any other color. To use this filter simple put the following two lines of code in your settings file: from sorl.thumbnail.defaults import PROCESSORS as THUMBNAIL_PROCESSORS THUMBNAIL_PROCESSORS = ('path.to.white_background',) + THUMBNAIL_PROCESSORS

  • png
  • background
  • sorl.thumbnail
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

Expire page from cache

A simple helper function that clears the cache for a given URL, assuming no headers. Probably best used when wired up to a model's post_save event via signals. See [message to django-users mailing list](http://groups.google.com/group/django-users/msg/b077ec2e97697601) for background.

  • cache
  • caching
  • expiration
Read More

2955 snippets posted so far.