Login

All snippets

Snippet List

models with order (+admin editing)

Use this abstract model if you want to add "order" to a given model. Once you do, you will get automatic "up" and "down" links for each model row. One problem is that if the user sorts by another row, the up and down links are still there, but now don't make a lot of sense.

  • models
  • admin
  • order
Read More

Autogenerate admin classes in admin.py

Tired of adding admin classes to admin.py whenever you add a model? This admin.py automatically keeps itself up-to-date with your models.py file. It assumes if you have a model: MyModel, you want an admin class called AdminMyModel. Regards, Luke Miller

  • django
  • models
  • admin
Read More

Django and jQuery -- pulling info from a long-running process

Another sample of how to integrate Django and jQuery. === This starts a function in views.py that takes a long time to finish. It sets a session variable so that another function can report on the situation. We use jquery and ajax to 'pull' that data from Django so as to provide a progress report. I don't yet know how to background a long-running process, but this is an okay stop-gap method to use. I hope. \d

  • ajax
  • json
  • jquery
  • data
  • progress
  • pull
Read More

Ajax form with jQuery

I recently got a form working via jQuery and Django. This was not easy for me to do and I thought I'd record my finding here. The form submits via jQuery and the "form" plugin. Please visit jQuery's home page to find all those links. This code handles: * urls.py -- passing both normal and 'Ajax' urls to a view. * views.py -- Handling both kinds of requests so that both normal and ajax submits will work. * The HTML template with the script for submitting and some bling. Error handling === I like to stay DRY so the idea of checking the form for errors in javascript *and* checking it in Django irks me. I decided to leave that up to Django, so the form submits and gets validated on the server. The error messages are sent back to the browser and then displayed.

  • ajax
  • urls
  • fields
  • views
  • jquery
  • form
  • errors
Read More

Cacheable resources

This snippet provides a template tag that automatically replaces references to any resource you want cached forever with a version of the file that is based on the MD5 sum. For an image, you would use something like: {% load utils %} <img src="{% cacheable "/media/images/logo.png" %}"/> To install it, put a setting in your settings.py file called "DOCUMENT_ROOT", put the python code into a templatetag-friendly file (e.g. app/templatetags/utils.py), load that template tag, then use either a string literal, as above, or a variable name to refer to your resource: <img src="{% cacheable my_media_file %}"/> The cacheable resource will be used when `DEBUG = False`, but in DEBUG mode, the path you give it will be passed back untouched (so you don't have a proliferation of cacheable files as you develop). Django will need write access to the directory you've specified as "DOCUMENT_ROOT" (so it can copy the original file into a forever-cacheable version). You'll also need to set up your webserver to serve files called "MYMD5SUMNAME.cache.(js|css|png|gif|jpg) with an expires header that is far into the future. The goal here is to create a version of your file that will never have to be downloaded again. If you ever change the original file, the MD5 sum will change and the changed file's cacheable name will reflect that. Besides simply changing the name of resources, if the file is a JavaScript or CSS file, and you've specified `MINIFY = True`, the file will be minified using YUI compressor.

  • md5
  • cacheable
  • cacheing
Read More

SiteRedirectMiddleware

Redirects to the default site (from Django's Sites contrib app), specified by the `SITE_ID` setting. That's for example useful if you configured your webserver to handle multiple domains with the same virtual host and want to make sure every requests is then redirected to the right domain.

  • middleware
  • sites
Read More

debug info middleware

Hi, I have developed a middleware that enables to view debugging information in production for a single user filtered by useragent or ip. The debug info is appended to the html code as a remark and can be viewed with a view source operation from the browser. Take a look at http://code.google.com/p/debugview/ Enjoy

  • middleware
  • django
  • debug
  • information
Read More

Translation statistics gatherer

A script that gathers statistics of translated, untranslated and fuzzy literals of translations (be it Django itself or a project using Django). For that it re-scans the tree and generates a up-to-date POT in a temporary location, so the statistics of translation "coverage" are calculated relative to the current status of the tree. It doesn't touch the tree it is analyzing at all. It should be run from the directory containing the `locale/` directory of your project or from the `django/` directory of a Django copy. It is based on the `makemessages` Django management command (or rather its previous standalone `make-messages.py` script incarnation) and uses the same command line switches: * `-d <domain>` -- `<domain>` is `django` or `djangojs`. Optional, defaults to `django`. * `-l <language>` OR * `-a` -- process all languages

  • internationalization
  • i18n
  • l10n
  • translations
  • status
  • statistics
  • localization
Read More

Serve static media and indexes from app directories [Python2.5, Development only]

This view serves static media and directory indexes for a django application. It should only be used in development, media should be provided directly by a web server in production. This view assumes a django application stores its media in app/media (which is very common) and the file is referred to in the templates by the last part of a django app path. e.g. As in django.contrib.admin -> 'admin'. First we check if the media is a request in an application directory; if so we attempt to serve it from there. Then we attempt to provide the document from the document_root parameter (if provided). To use this view you should add something like the following to urls.py: ` if settings.DEBUG: urlpatterns += (r'^media/(?P<path>.*)$', 'site.media.serve_apps', {'document_root' : settings.MEDIA_ROOT}) ` You can then have the admin media files served by setting ADMIN_MEDIA_PREFIX = '/media/admin/'

  • media
  • static-media
  • directory-index
Read More

Manager method for limiting GenericForeignKey queries

This is a simple manager that offers one additional method called `relate`, which fetches generic foreign keys (as referenced by `content_type` and `object_id` fields) without requiring one additional query for each contained element. Basically, when working with generic foreign keys (and esp. in the usecase of having something like a tumblelog where you use an additional model just to have a single sorting point of multiple other models), don't do something like `result = StreamItem.objects.select_related()` but just fetch the content type with `result = StreamItem.objects.select_related('content_type')`, otherwise you will end up with first one query for the list of StreamItems but then also with one additional query for each item contained in this resultset. When you now combine the latter call with `result = StreamItem.gfkmanager.relate(result)`, you will just get the one query for the item list + one query for each content type contained in this list (if the models have already been cached). For further details, please read [this post](http://zerokspot.com/weblog/2008/08/13/genericforeignkeys-with-less-queries/) on my blog.

  • foreignkey
  • generic
  • manager
  • query
  • tuning
Read More

3110 snippets posted so far.