Login

Top-rated snippets

Snippet List

Save a model using an arbitrary db connection

This function lets you save an instance of a model to another database based on a connection argument. Useful when doing data migrations across databases. Connection is anything that would work as a django.db.connection I'm not sure if this handles proxy models or model inheritance properly, though.

  • multi-db
  • connection
Read More

Fix duplicate first page of paginated results

Search engines might conclude there's duplicate content if `/some_view/` and `/some_view/?page=1` returns the same results. This middleware redirects `?page=1` to the URL without the page parameter. You can set the name of the parameter in settings.py as `PAGE_VAR`. See [here](http://www.muhuk.com/2009/08/a-civilized-way-display-lots-of-data/) for more details.

  • middleware
  • pagination
  • seo
  • paginate
Read More

Template Filter: Add indentation

Template filter to add the given number of tabs to the beginning of each line. Useful for keeping markup pretty, plays well with Markdown. Usage: {{ content|indent:"2" }} {{ content|markdown|indent:"2" }}

  • filter
  • markup
  • pretty
  • indent
  • indentation
Read More

is_dirty and dict of changed values

When you call model.changed_columns() you get a dict of all changed values. When you call model.is_dirty() you get boolean whether or not the object has been changed since last save Based on an answer here:http://stackoverflow.com/questions/110803/dirty-fields-in-django but fixed and added is_dirty

  • django
  • models
  • save
  • dirty
Read More

Redirect view based on GEO

Wanted a neat way to redirect views based on GeoIP determined criteria, from HTTP_REFERER. Decorator approach seemed the best way to make it straightforward to redirect views. To use, installed the Max Mind Python GeoIP API : http://www.maxmind.com/app/python

  • view
  • redirect
  • geoip
Read More

Choices helper

A quick and dirty helper for model field `choices`. It's not perfect, but this is what I use.

  • models
  • choices
Read More

File storage with a better rename method

A file storage which uses a more sane rename method for existing files. Add `DEFAULT_FILE_STORAGE = 'site.storage.BetterNameFileSystemStorage'` (obviously changing `site.storage` to the module which you put this inside)

  • file-storage
Read More

Media RSS generation for Photologue

Provides a basic implementation of Yahoo's [MediaRSS](http://video.search.yahoo.com/mrss) format for [Photologue](http://code.google.com/p/django-photologue/) galleries Simplest usage: I have feedgenerator.py in a utils directory. Import photofeeds and hook up the feed url in your URLConf: from utils.feedgenerator import photofeeds urlpatterns += patterns('', url(r'^feeds/(?P<url>.*)/$', 'django.contrib.syndication.views.feed', {'feed_dict': photofeeds}),) Without customization, this will generate a feed for the gallery archive at `/feeds/gallery/` It will contain a single photo per gallery, as returned by Gallery.sample() Additionally, each gallery has a dynamic feed available at the url via Gallery.title_slug: `/feeds/gallery/gallery-title-slug/` This feed will contain an Item for each Photo in the Gallery All that is left is to add an autodiscovery feed to your pages in &lt;head&gt;. An RSS agent like CoolIris can then parse your gallery and provide a slick view of your photos. e.g Add something like this to gallery_detail.html: `<link rel="alternate" href="/feeds/gallery/{{ object.title_slug }}/" type="application/rss+xml" title="Photologue Gallery - {{ object.title }}" id="gallery_feed" /> `

  • feed
  • rss
  • photologue
  • syndication
Read More

Clear FileField/ImageField files in the Admin

The widget for FileField and ImageField has a problem: it doesn't supports clear its value and it doesn't delete the old file when you replace it for a new one. This is a solution for this. It is just for Admin, but you can make changes to be compatible with common forms. The jQuery code will put an **<input type="checkbox">** tag next to every **<input type="file">** and user can check it to clear the field value. When a user just replace the current file for a new one, the old file will be deleted.

  • admin
  • jquery
  • imagefield
  • filefield
Read More

User manager

If you have a model with foreign key to User, you can use this manager to show (i.e. in admin interface) only objects, that are related to currently logged-in user. Superuser sees all objects, not only his. Requires: [ThreadlocalsMiddleware](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser)

  • filter
  • foreignkey
  • user
  • manager
  • queryset
  • owner
  • users
  • user-foreign-key
Read More

another UserForeignKey

This is another foreign key to User model. User is automatically associated before save. Requires: [ThreadlocalsMiddleware](http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser) Inspired by: [snippet 509](http://www.djangosnippets.org/snippets/509/)

  • foreignkey
  • model
  • user
  • field
  • users
  • user-foreign-key
Read More

Localeurl sitemap

Example of using django localeurl with sitemaps. Create sitemap instance for each combination of the sitemap section and language. In your sitemap class create method ` def location(self, obj): return chlocale(obj.get_absolute_url(), self.language) ` or inherit it from LocaleurlSitemap class.

  • localeurl
  • sitemap
Read More

Improved model select field for generic relationships

Browse through the installed models using the content types framework. There are two difference in behavior with respect to the default field: 1. if a model provides a translation for its name (e.g.: verbose_name and/or verbose_name_plural), it shows that rather than a raw model name 2. allow to filter the models shown through the use of `choice` parameter Example: `mbf = ModelBrowseField(choices=['User', 'Session'])`

  • models
  • form
  • field
  • contenttypes
  • translation
  • browse
Read More

Export Related as JSON Admin Action

[The Django Admin Action documentation leads you through exporting a queryset to JSON](http://docs.djangoproject.com/en/dev/ref/contrib/admin/actions/#actions-that-provide-intermediate-pages). However exporting from a single model rarely tells the whole story. Using the CollectObjects class, `export_related_as_json` gathers all instances related by foreign keys to what is being exported and exports them as well in a serialization bonanza. Use it to export Users and you'll get their Profile objects as well! **Usage** # admin.py from django.contrib import admin admin.site.add_action(export_related_as_json)

  • serialize
  • admin
  • json
  • export
  • admin-action
Read More

3110 snippets posted so far.