Login

All snippets written in Python

Snippet List

Proper fixtures loading in south data migrations

South documentation [contains a description](http://south.readthedocs.org/en/0.7.6/fixtures.html#fixtures-from-migrations) of the way you can load fixtures inside the data-migrations. def forwards(self, orm): from django.core.management import call_command call_command("loaddata", "my_fixture.json") It seems pretty clear and easy, but in fact it does not work the way you expect from south migrations, because the fixture loading does not engage the **orm** object. So, it allows **loaddata** management command to use standard models loading mechanism, and it would provide the most recent version of the models, obviously, which may not correspond to the schema of the fixture`s data. To be ensured that migration will use appropriate version of the models for fixture loading you could use code like follows: class Migration(DataMigration): def forwards(self, orm): load_fixture('my_fixture.json', orm) class Migration(DataMigration): def forwards(self, orm): with southern_models(orm): call_command("loaddata", "my_fixture.json")

  • fixtures
  • migration
  • fixture
  • south
  • datamigration
Read More

Class-based view mixin for flatpages

Allows you to include content from flatpages in class-based views. You can specify the url for the flatpage you want, or let it be determined by request.path.

  • mixin
  • flatpages
  • class-based-views
Read More

Header view decorators

This file includes two Django view decorators `header` and `headers` that provide an easy way to set response headers. Also, because I have to work with a lot of cross domain requests, I include few shortcuts for convenience to set the Access-Control-Allow-Origin header appropriately.

  • views
  • view
  • decorator
  • headers
  • decorators
  • header
Read More
Author: ydm
  • 1
  • 1

Gravatar support in model save override

Overridden save() method that adds Gravatar support for a user with a profile photo field (and presumably an email field). Checks to see if user has provided a photo. If not, then query Gravatar for a possible photo. Finally, if Gravatar does not have an appropriate photo for this user, then use whatever default photo is available (in this case, 'users/photos/default_profile_photo.png'... change as necessary).

  • model
  • save
  • override
Read More

CompressedTextField for Django 1.4+

This snippet *updates* http://www.djangosnippets.org/snippets/383/ and http://www.djangosnippets.org/snippets/1495/ for Django 1.4+, and adds support for sqlite3 and south. Original snippet text: A CompressedTextField to transparently save data gzipped in the database and uncompress at retrieval.

  • text
  • model
  • field
  • compressed
  • gzip
  • south
Read More

Template {% macro %} support, with context rendering

Reuse blocks of template code and content as macros. This is a small extension of https://gist.github.com/skyl/1715202 (which was based on http://djangosnippets.org/snippets/363/) to support rendering macro output into context variables. See comments for details.

  • template
  • tag
  • macro
Read More

Retrieve human-readable value from choices tuple or value from dict

Will help you retrieve the value from a dictionary with a supplied key, or the human-readable value from a choices tuple. Works as follows: To retrieve the value of a dict: `{{ crime_rates_dict|getval:"Chicago" }}` <-- will return value of `crime_rates_dict["Chicago"]` To retrieve the human-readable value from a choices tuple: `{{ country.COUNTRIES|getval:"US" }}` <-- will return "United States" in `COUNTRIES = (("US", "United States"),)`

  • template
  • templatetag
  • choices
  • dict
  • tuple
Read More

Custom collectstatic that uses etag and md5 digests to determine whether files on S3 have changed

For use with S3 BotoStorage STATICFILES_STORAGE ="storages.backends.s3boto.S3BotoStorage" and AWS_PRELOAD_METADATA = True Custom management command that compares the MD5 sum and etag from S3 and if the two are the same skips file copy. This makes running collect static MUCH faster if you are using git as a source control system which updates timestamps.

  • s3
  • amazon
  • aws
  • boto
  • collectstatic
  • storages
Read More

decorator to add GUID Field to Django Models

A decorator to add a GUID Field to a Django Model. There are other bits of code out there that do similar things, but it was important for the field to have a unique value _before_ it is saved in the database. The contribute_to_class method therefore registers the field class with the post_init signal of the class it's being added to. The handler for that signal is where field initialization is done.

  • models
  • fields
  • decorators
Read More

Allow foreign key attributes in list_display with '__'

This snippet provides a subclass of admin.ModelAdmin that lets you span foreign key relationships in list_display using '__'. The foreign key columns are sortable and have pretty names, and select_related() is set appropriately so you don't need queries for each line. EDITS: * Fixed error when DEBUG=False. * Broke out `getter_for_related_field` so you can override short_description manually (see example). * Added regular foreign key fields to select_related(), since this is overriding the code in ChangeList that usually does it.

  • admin
  • foreign-key
  • list_display
Read More

Custom change_list filter based on SimpleListFilter shows only referenced (related, used) values

Since Django 1.4 you can create your own filters for change list view. If you want to show just used/related items in filter chooser you can use this snippet. Original idea from [here](http://jmduke.net/post/39953950546/custom-admin-filters-in-django). Big thanks to author. Improved class names for better clarity and use of model_admin.model instead of hardcoded model name. In example you can see two models - City and Country. City has ForeignKey to Country. If you use regular list_filter = ('country',) you will have all the countries in the chooser. This snippet however filters only related countries - the ones that have at least one relation to city.

  • ForeignKey
  • Filter
  • SimpleListFilter
Read More

fast non-locale aware float format

Django's `floatformat` is a good way to format a number if you require a specific amount of decimals. It is, however, very slow. In testing each `floatformat` call took 200–250 us, which means it'll take a second to render a page that floatformats 4000 numbers. Much of the time comes from using `Decimals`. I looked at using the `cdecimal` module, and while it improved the speed, each call still clocked in at between 80 and 100 us. `fast_floatformat` is not locale aware, and doesn't look at Django settings for USE_THOUSAND_SEPARATOR, but it'll take between 1.2 and 3 us per call for ints, floats and strings, and about 12 us per call for Decimals, giving you up to 800000 floatformatted numbers per second.

  • floatformat
Read More

Coffeescript compilation

All I wanted was for one to one compilation of coffeescript to javascript. * Without special templatetags * Without specifying explicit bundles * Served dynamically in development * Compiled by collectstatic for producton This code is the minimum required for this. There are two things to take into account: * list method to find coffeescript files to compile for collectstatic * find method to find coffeescript equivalent for a js file for django.contrib.staticfiles.views.serve. The list method will use the list method on all finders that come before it in STATICFILES_FINDERS to find all the files that end with .coffee and will return the equivalent .js path with a storage class that knows how to compile the coffeescript. The find method will use the find method on all finders that come before it in STATICFILES_FINDERS to locate the coffeescript file that is actually being requested. It will then compile the coffeescript into a file in settings.CACHE_DIR before serving that file.

  • development
  • staticfiles
  • coffeescript
  • collectstatic
Read More

2955 snippets posted so far.