Login

All snippets written in Python

2956 snippets

Snippet List

Command Line Script Launcher

I often write short test or development scripts that are intended as one-offs. I typically want to execute these scripts from the command line but am always forgetting the necessary steps to set up the Django environment [as described here][bennett]. This snippet allows you execute arbitrary Python scripts from the command line with the context of a given project: python manage.py execfile /path/to/some/script.py Add the code to a file named `execfile.py` within the `management/commands` directory of one of your apps ([see here][ref] for details). [ref]: http://www.djangoproject.com/documentation/django-admin/#customized-actions "Customized Actions" [bennett]: http://www.b-list.org/weblog/2007/sep/22/standalone-django-scripts/ "Standalone Django Scripts"

  • script
  • management
  • execfile
Read More

Dynamic Django settings context processor

Here's a nice way of easily passing only certain settings variables to the template. Because of the way Django looks up context processors, we need a little hack with sys.modules. The [blog entry is here](http://sciyoshi.com/blog/2008/jul/10/dynamic-django-settings-context-processor/).

  • dynamic
  • settings
  • context
  • processor
Read More

Allow template tags in a Flatpage's content

** This tag, as shown, can cause problems (infinite recursion being one) if you don't use it correctly. ** Our internal CMS has a pages app similar to Flatpages, and a "chunks" app similar to [django-chunks](http://blog.clintecker.com/2008/jul/6/django-chunks/). Because most of our other apps are template-tag driven (FAQs, job postings, news, events, etc) I wanted a way to be able to write django template code right into a page or chunk's body from within the django admin. This tag will let you write django template code into, for example, a Flatpage's content and render it with the current context. So if you had a template tag called "get_latest_news" and wanted to add latest news to a flatpage, just enter this in the flatpage's content: {% get_latest_news 5 as news %} {% for article in news %} <li>{{ article.title }}</li> {% endfor %} This ability has proven extremely useful to us. Please note this is just a "summary" snippet to illustrate the concept. Use in a production environment should include more robust error checking.

  • template
  • flatpages
Read More

i18n base model for translatable content

Together with my mentor, Dusty Phillips, I have developed a simple class that dynamically adds two fields to its subclasses. This is useful in cases when a single piece of content is divided into translatable and non-translatable fields, connected by a 1-to-many relationship. ## Update 2009/03/30 Since its inception, this snippet has grown into a significantly more powerful solution for translatable content (I use it myself with great joy :). The project is now hosted on github: [project page](http://github.com/foxbunny/django-i18n-model/tree/master) ## Update 2008/07/09 It is now possible to define `i18n_common_model` attribute in `class Meta` section. Here's an example: class Meta: i18n_common_model = "MyCommonModel" As you can see, it has to be a string, not the real class, and it is case-sensitive. ## Example class Article(models.Model): author = models.CharField(max_length = 40) class Admin: pass class ArticleI18N(I18NModel): title = models.CharField(max_length = 120) body = models.TextField() class Admin: pass # optionally, you can specify the base class # if it doesn't follow the naming convention: # # class Meta: # i18m_common_model = "Article" When the ArticleI18N class is created, it automatically gains two new fields. `lang` field is a CharField with choices limited to either `settings.LANGUAGES` or `django.conf.global_settings.LANGUAGES`. The other field is `i18n_common` field which is a ForeignKey to Article model. ## The conventions * call the translation model `SomeBaseModelI18N`, and the non-translation model SomeBaseModel (i.e., the translation model is called basename+"I18N") * the first convention can be overriden by specifying the base model name using the `i18n_common_model` attribute in `Meta` section of the `I18N` model * I18N model is a subclass of `I18NModel` class ## Original blog post [http://blog.papa-studio.com/2008/07/04/metaclasses-and-translations/](http://blog.papa-studio.com/2008/07/04/metaclasses-and-translations/)

  • models
  • i18n
  • metaclass
  • translated-content
Read More

BBCode templatefilter (generate & strip)

Parse a string for [BBCode](http://en.wikipedia.org/wiki/Bbcode) and generate it to (X)HTML by using the [postmarkup libary](http://code.google.com/p/postmarkup/). In your template for generating (X)HTML: {% load bbcode %} {{ value|bbcode }} In your template for removing BBCode fragments: {% load bbcode %} {{ value|strip_bbcode }}

  • template
  • templatetag
  • templatefilter
  • bbcode
  • xhmtl
Read More
Author: b23
  • 2
  • 8

Locking tables

Sometimes you need to prevent concurrent access to update/calculate some properties right. Here is (MySQL) specific example to lock one table with new object manager functions.

  • model
  • mysql
  • manager
  • table
  • lock
Read More

easy absolute path for settings.py

when you deploy djangos apps, some servers have problems resolving the absolute path of some files (e.g: sqlite3 + lighttpd + apache), using the snippet above solves this issue :)

  • settings
Read More

Model with random ID

An abstract model base class that gives your models a random base-32 string ID. This can be useful in many ways. Requires a Django version recent enough to support model inheritance.

  • model
  • random
  • model-inheritance
  • id
  • primary-key
Read More

Ajax API class

Whip up an AJAX API for your site in a jiffy: class MySite(AJAXApi): @AJAXApi.export def hello(request): return {'content': self.get_content()} def get_content(self): return 'Hello, world!' urlpatterns += MySite().url_patterns() (the example needs the JSON encoding middleware of [snippet 803](http://www.djangosnippets.org/snippets/803/) to work.) The secret is that bound instance methods are callable too, so work as views. (Most Django people only use functions, or sometimes classes with `__call__`, as view functions.) You get implicit type dispatch off that `self` object. So you could subclass `MySite`, change `get_content`, and still use the same `hello` method. See (django-webapp)[http://code.google.com/p/django-webapp/] for a REST-ish Resource class using this same idea. You can clearly do better than my `func_to_view`, and also make a better decorator than `exported` (so you can actually say `@exported('name') def function()` etc.). This is more of a proof of concept that should work for most people. Caveat: I've changed a few things since I last really tested this. (psst, this also works for non-AJAX views too.)

  • ajax
  • api
  • instance-view
Read More

Another JsonResponse

Another `JsonResponse` class, including comment wrapping. Extensions to other kinds of CSRF protection should be obvious. Good explanations of why such protections are needed would make excellent comments on this snippet. This depends on the `json_encode` method in [snippet 800](http://www.djangosnippets.org/snippets/800/).

  • json
  • response
  • jsonresponse
Read More

Extended JSON encoder

The Django JSON encoder already extends the `simplejson` encoder a little; this extends it more and gives an example of how to go about further extension. Hopefully `newserializers` (see the community aggregator today) will supercede this, but until then, it's useful.

  • serialize
  • json
  • serializer
Read More

DebugFooter middleware with Pygments sql syntax highlighting

Based on Snippet [766](http://www.djangosnippets.org/snippets/766/) but added syntax highlighting of the sql output via [pygments](http://pygments.org/). The sql output will also be wrapped at 120 characters by default (can be configured by changing WRAP). It degrades nicely if pygments is not installed. This will add quite some cpu-cycles just for printing debug messages so use with care. Following is the rest of the original description by [simon](http://www.djangosnippets.org/users/simon/) (shamelessly copied): Adds a hidden footer to the bottom of every text/html page containing a list of SQL queries executed and templates that were loaded (including their full filesystem path to help debug complex template loading scenarios). To use, drop into a file called 'debug_middleware.py' on your Python path and add 'debug_middleware.DebugFooter' to your MIDDLEWARE_CLASSES setting. Edit: Added the ability to set the height of the debug-box

  • sql
  • middleware
  • debugging
Read More