Login

Top-rated snippets

Snippet List

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

Imagefield with variations

Usage: from django.db import models from imagevariations.fields import ImageVariationsField, Thumbnail class Image(models.Model): name = models.CharField(max_length=20) image = ImageVariationsField(upload_to='testimages', variations=(Thumbnail,) ) How to use in templates: Use the lowercase name of the image variation class. {{ object.image.variations.thumbnail.url }} By default all image variations will use the same storage backend as the field but can be replaced per variation by setting self.storage on the variation class.

  • thumbnail
  • imagefield
  • variations
Read More

FileField with file extension whitelist

A simple FileField with a addition file extension whitelist. Raised ValidationError("Not allowed filetype!") if a filename contains a extension witch is not in the whitelist.

  • forms
  • filefield
Read More

auto image field w/ prepopulate_from & default

Given such code: class ProductImage(models.Model): fullsize = models.ImageField(upload_to= "products/%Y/%m/%d/") display = AutoImageField(upload_to= "products/%Y/%m/%d/",prepopulate_from='fullsize', size=(300, 300)) thumbnail = AutoImageField(upload_to="products/%Y/%m/%d/",null=True,default='/media/noimage.jpg')) display will be automatically resized from fullsize, and thumbnail will default to /media/noimage.jpg if no image is uploaded Note: At some point the code broke against trunk, which has now been updated to work properly

  • image
  • models
  • db
  • field
Read More

Minify JS template tag

Uses JSMin. Python version available from [http://www.crockford.com/javascript/jsmin.py.txt](http://www.crockford.com/javascript/jsmin.py.txt) Provides template tags to minify JavaScript on the fly. `{% minifyjs %}[code]{% endminifyjs %}`

  • template
  • tag
  • javascript
  • js
  • minify
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

Models for Postal Addresses

Here's some fairly normalized models for representing postal addresses. Making postal_code a separate model would probably be the only way to get it to a level that everyone would agree is 2NF, but we handle a lot of international addresses so that isn't really feasible. Country and StateProvince are intended to be populated with data from ISO 3166. I'd include the SQL I used with that data, but it's very long and there's no attach feature. Also, I'd probably be violating ISO's copyright.

  • models
  • countries
Read More

CustomQueryManager

A `models.Manager` subclass that helps to remove some of the boilerplate involved in creating managers from certain queries. Usually, a manager would be created by doing this: class MyManager(models.Manager): def get_query_set(self): return super(MyManager, self).get_query_set().filter(query=blah) Other managers may return other query sets, but this is especially useful as one may define queries on a table which would be used a lot. Since the only part that ever changes is the `query=blah` set of keyword arguments, I decided to abstract that into a class which, besides taking the repetition out of manager definition, allows them to be and'd and or'd in a manner similar to the `Q` objects used for complex database queries. `CustomQueryManager` instances may be defined in one of two ways. The first, more laborious but reusable manner, is to subclass it, like so: class MyManager(CustomQueryManager): query = Q(some=query) Then, `MyManager` is instantiated with no arguments on a model, like normal managers. This allows a query to be reused without extra typing and copying, and keeps code DRY. Another way to do this is to pass a `Q` object to the `__init__` method of the `CustomQueryManager` class itself, on the model. This would be done like so: class MyModel(models.Model): field1 = models.CharField(maxlength=100) field2 = models.PositiveIntegerField() my_mgr = CustomQueryManager(Q(field1='Hello, World')) This should mainly be used when a query is only used once, on a particular model. Either way, the definition of `__and__` and `__or__` methods on the `CustomQueryManager` class allow the use of the `&` and `|` operators on instances of the manager and on queries. For example: class Booking(models.Model): start_date = models.DateField() end_date = models.DateField() public = models.BooleanField() confirmed = models.BooleanField() public_bookings = CustomQueryManager(Q(public=True)) private_bookings = public_bookings.not_() confirmed_bookings = CustomQueryManager(Q(confirmed=True)) public_confirmed = public_bookings & confirmed_bookings public_unconfirmed = public_bookings & confirmed_bookings.not_() public_or_confirmed = public_bookings | confirmed_bookings public_past = public_bookings & Q(end_date__lt=models.LazyDate()) public_present = public_bookings & Q(start_date__lte=models.LazyDate(), end_date__gte=models.LazyDate()) public_future = public_bookings & Q(start_date__gt=models.LazyDate()) As you can see, `CustomQueryManager` instances can be manipulated much like `Q` objects, including combination, via `&` (and) and `|` (or), with other managers (currently only other `CustomQueryManager` instances) and even `Q` objects. This makes it easy to define a set of prepared queries on the set of data represented by a model, and removes a lot of the boilerplate of usual manager definition.

  • models
  • q
  • manager
  • query
  • custom
Read More

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

3110 snippets posted so far.