Login

All snippets

Snippet List

Debug Page Load Time Stats Middleware

Use this to display a split of page execution time between python and the db in your base template when debugging. I originally got the base of this code from another snippet, but I can't find it anymore and want to share with new folks because I find this handy.

  • middleware
  • profile
  • time
  • debug
  • performance
  • query
  • basetemplate
Read More

Sphinx Search ORM / Revised

A revised version of [zeeg's Sphinx Search ORM](http://www.djangosnippets.org/snippets/231/), using my Sphinx client and adding support for Sphinx's excerpt generator. It's still missing support for search modes/order_by/filter/exclude, but it should be easy and I will add the relevant methods soon as I need them. Usage is the same as zeeg's class, except that you can pass a field name (or tuple for related objects) to its constructor, that will be used for excerpts: class MyModel(models.Model): search = SphinxSearch(excerpts_field='description') MyModel.search.query('query') MyModel.search.query('query').count() Returns an ordered list of the objects in your database.

  • search
  • sphinx
  • full-text
Read More

Using descriptors for lazy attribute caching

Python's [descriptor][1] protocol can seem a bit esoteric at first; however, it can be invaluable in handling everyday idioms and patterns - something that the Django framework authors have taken advantage of in numerous occasions (e.g.: [auth middleware][2]). One such idiom I see and use often and would like to generalize is the attribute-existence check-or-set routine illustrated here: def get_foo(self): if not hasattr(self, '_foo'): self._foo = init_foo() return self._foo Rather than coding this up multiple times (either for a given class or across many unrelated classes), I would prefer to delegate this repetitive work to a descriptor and remain [DRY][3]. The means to this end is implemented as a variation on the Python `property` construct, and is intentionally over simplistic (I leave the details of the heavy lifting up to the reader). The basic premise shown in source here is simply straight-forward Python, a quick and dirty example of how it could be utilized within a Django context is shown here: from django.db import models from cacheprop import CacheProperty2 ARTIFACT_TYPES = ( ('F', _('File')), ('D', _('Directory')), ('A', _('Alias')), ) class Artifact(models.Model): # model fields name = models.CharField(maxlength=64) type = models.CharField(maxlength=1, choices=ARTIFACT_TYPES) file_metadata = CacheProperty2( lambda self: self.filemetadata_set.get(artifact__id=self.id) ) class FileMetadata(models.Model): byte_size = models.IntegerField() artifact = models.ForeignKey(Artifact, unique=True) [1]: http://users.rcn.com/python/download/Descriptor.htm [2]: http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/middleware.py [3]: http://c2.com/cgi/wiki?DontRepeatYourself

  • python
  • descriptors
Read More

Never cache a group of URLs

This is a special URL patterns replacement that prevents caching of any URL listed within it. We needed this in Review Board to prevent the JSON API function results from being cached in Internet Explorer.

  • urls
  • cache
  • url
  • patterns
Read More

Querying on existence of a relationship

When you have two models joined by a foreign key, it's common to want to retrieve a set of objects from the "target" of the foreign key based on whether there are any objects "pointing" to them. This snippet demonstrates how to do so, using the `extra` method of the default model manager. Note that this is probably more efficient than using two ORM methods (e.g., selecting all values from one table, and using an `id__in` lookup on the other) since it does the whole thing in one query and avoids instantiating any intermediate objects.

  • models
  • orm
  • foreign-keys
Read More

SAS70 Compliant Password Validator

Validator to verify a password is SAS70 compliant: greater than or equal to eight characters, and contains at least three out of the four characters( Uppercase, Lowercase, Number, Special Character ).

  • validator
Read More

XhtmlDegraderMiddleware

The XhtmlDegraderMiddleware class is designed to make it easier to deploy XHTML contents onto the World Wide Web. The correct MIME media type for sending XHTML is `application/xhtml+xml` -- the `text/html` media type is also acceptable provided [certain guidelines](http://www.w3.org/TR/2002/REC-xhtml1-20020801/#guidelines) are followed. The vast majority of web browsers released from 2002 onwards have good XHTML support; this includes Mozilla Firefox, Opera, and Apple Safari. Two notable exceptions are Internet Explorer 7.0 and Netscape Navigator 4.8; instead of displaying XHTML, they present the user with a download dialog instead. The role of the XHTML Degrader, then, is to automatically detect when browsers do not support XHTML, and to degrade the contents into something they're capable of rendering. **How it works** XhtmlDegraderMiddleware checks the content type of all HTTP responses. If the XHTML media type is set, the `Accept` request header is examined to determine whether the user agent actually supports XHTML. If so, the contents is sent unaltered. If not, a number of silent changes are made to make the response more friendly to XHTML-challenged browsers and web crawlers. Firstly, the `Content-Type` header is set to the HTML media type. Any XML processing instructions are removed, and a `DOCTYPE` is added if none is present. In the case of Internet Explorer, this should ensure the content is rendered in "standards compliance" mode. Empty elements are made to have a space before their trailing slash. N.B. If an HTTP response is already set to `text/html`, or set to any media type other than `application/xhtml+xml`, the middleware will have no effect. Note also that if you use GZipMiddleware, you should ensure that it appears in your MIDDLEWARE_CLASSES setting before XhtmlDegraderMiddleware, to allow the XHTML Degrader to act first.

  • middleware
  • xhtml
Read More
Author: dmh
  • 4
  • 4

pygments stylize

Simple tag to enable easy parsing of inline code within a template. Usage: {% stylize "language" %}...language text...{% endstylize %}. Make sure to set the language for Pygments to parse as the first argument to the tag. You will also need to include a copy of the CSS that Pygments uses. The [Pygments](http://pygments.org/) library is required for this tag.

  • pygments
  • templatetags
Read More

Automatic Paragraphs

I just converted the autop filter from Drupal (which is itself based on a Wordpress filter) from PHP to Python. I had to change the format of the regular expressions a bit and make them raw strings, but otherwise the function is unchanged. It should work exactly like the original function.

  • filter
  • text
  • format
Read More

common model privacy

A BooleanField indicating privacy is common on models, but the name of the field and whether the field being True indicates private or public both may change across models. If there is more than one potentially private model, a common interface is needed. A commonly-named method would do the job with `[a for a in MyModel.objects.all() if not a.is_private()]`, but it would still retrieve private instances from the database only to filter them out. This approach puts the name of the privacy field and whether that field being True indicates private or public in a tuple attribute of the model class. A chainable method is added to all QuerySet objects. example use: class MyModel(models.Model): is_public = models.BooleanField(default=True) # ... privacy_field = ("is_public", False) \>\>\> publicMyModels = MyModel.objects.all().exclude_private() \>\>\> values = publicMyModels.values()

  • models
  • querysets
Read More

Menu/navigation bars in a tag

This tag makes it easy to include menu or navigation bars in an application's pages, even in a 'tabbed' fashion. (The actual appearance is styled in CSS; this example uses UL tags that are then supposed to be styled by a "display: inline" attribute to be rendered as horizontal bars.)

  • tag
  • menu
  • navigation
  • menubar
  • navbar
Read More
Author: ep
  • 4
  • 12

Default Template Loading

One of the things about Django that has always irked me is that there seems to be no standard facility for just loading a page and displaying it, simply. Yes, there is the flatpages module, but it is primarily designed for loading content from a DB. While you specify a custom template and put in junk values for the DB content, it just feels like extra, unnecessary work. Thinking about the problem some more, I borrowed from the idea of flatpages and implemented a view that will load an otherwise unmapped template off the filesystem and render it. This is very useful when converting an existing site over. Just copy your files over. No need to map anything in the URL conf or use the admin to add any flatpage entries. Since it'll render the template, too, you can even use tags and what not, so it need not be a static page.

  • template
  • loader
Read More

Db Mock

I hate when my unittest hits database. Especially when each test case needs different dataset. So I wrote this db mock, that's local to specific test and uses sqlite3 in-memory db. Usage (nosetests): class TestMainNoData(DbMock): 'testing main function with no meaningful data' def test_no_posts(self): 'there are no posts' assert models.Post.objects.count() == 0, 'should be no feeds'

  • testing
  • unittest
  • database
  • test
Read More

SQL Log Middleware + duplicates

This is based on [Snippet 161](/snippets/161/) It marks duplicated SQL queries. To avoid duplicates read: [Caching and Queryset](http://www.djangoproject.com/documentation/db-api/#caching-and-querysets) Sept. 07: Updated for current trunk: 'response' behaves like 'response.header' 22. October '07: Log into directory.

  • sql
  • middleware
  • log
  • profile
  • debug
Read More

3110 snippets posted so far.