Login

All snippets written in Python

2956 snippets

Snippet List

Generic Autodiscovery

Admin-like autodiscover for your apps. I have copy/pasted this code too many times...Dynamically autodiscover a particular module_name in a django project's INSTALLED_APPS directories, a-la django admin's autodiscover() method.

  • autodiscover
Read More

Model field choices as a namedtuple

This is a very flexible and concise way to [Handle choices the right way](http://www.b-list.org/weblog/2007/nov/02/handle-choices-right-way/) in model fields. * Preserves order. * Allows both a human-readable value for display in form `<select>`s as well as a code-friendly short name. * Mimic's Django's canonical [choices format](http://docs.djangoproject.com/en/1.3/ref/models/fields/#choices). * Doesn't restrict the value type. * Memory efficient. Inspired by [snippet 2373](http://djangosnippets.org/snippets/2373/) to use namedtuples as model field choices.

  • choice
  • choices
  • field
Read More

HammeringMiddleware

A middleware which will protect from page hammering using flexible spanning time windows using the cache backend. Please read the Docstring of the class for details.

  • middleware
  • spam
  • security
  • refresh
  • protection
  • hammering
  • django-newcache
Read More

astimezone template tag

should probably be migrated to an inclusion tag to allow a source timezone that isn't the site specific TIME_ZONE. This code assumes that your database stores dates according to the django.conf.settings.TIME_ZONE variable. Yes.. this assumes that dates are stored in the database according to system time. On my systems the system time of a server is always UTC therefore avoiding problems with datetime (no tz info) columns in backend databases having no timezone information and stored according to the database or system timezone information. I find it a good practice to always use UTC for any stored information and always retrieve information as UTC and localize the date during display.

  • templatetag
  • datetime
  • timezone
  • pytz
Read More

Server Side Cursors for Django's psycopg2 Backend

Based on discussion on [http://thebuild.com/blog/2010/12/14/using-server-side-postgresql-cursors-in-django/](http://thebuild.com/blog/2010/12/14/using-server-side-postgresql-cursors-in-django/) and [http://thebuild.com/blog/2010/12/13/very-large-result-sets-in-django-using-postgresql/](http://thebuild.com/blog/2010/12/13/very-large-result-sets-in-django-using-postgresql/) but instead implements them via extending the psycopg2 backend which allows you to use all of django's machinery without having to resort to using raw cursors. Usage: qs = Model.objects.all() with server_side_cursors(qs, itersize=100): for item in qs.iterator(): item.value if random_reason_to_break: break Setup: In your own project create the package hierarchy myproject.db.backends.postgresql_psycopg2 and place the code in base.py. In your settings.py set the database ENGINE to be 'myproject.db.backends.postgresql_psycopg2'. If you using south you'll have to let it know its a postgresql_psycopg2 backend by adding to SOUTH_DATABASE_ADAPTERS (see south documentation). Note: Make sure your using psycopg >= 2.4 for efficient named (server side) cursor iteration.

  • django
  • server
  • backend
  • cursors
  • named
  • psycopg2
  • side
Read More

Better Django Model Field Choices

Nice to name your constant multiple choice fields in models, this is one way of doing that. Sorry I haven't looked into existing alternatives. But this approach worked for me.

  • choice
  • choices
  • model
  • field
Read More

Get default form data

Given an unbound form, determine what data would be generated from POSTing the form unchanged. The goal is to end up with a dict such that, passed into another form constructor as its data kwarg, form.changed_data == [].

  • forms
  • widgets
Read More

Django 1.2 template tag {% IF %} with {% ELIF %} support

Adds to Django 1.2 tag `{% elif %}` {% if user.nick == "guest" %} Hello guest! {% elif user.nick == "admin" or user.is_admin %} Hello admin! {% elif user %} You are registered user {% else %} Login to site {% endif %} Snipped designed for [gaeframework.com](http://www.gaeframework.com) Inspired by snippets: [#1572](http://djangosnippets.org/snippets/1572/) and [#2243](http://djangosnippets.org/snippets/2243/)

  • template
  • if
  • elif
  • django 1.2
  • tags. tag
Read More

Custom filename example with sorl-thumbnail

usage :- put it in python path and refer to it from settings.py `THUMBNAIL_BACKEND = 'full.import.path.to.SEOThumbnailBackend'` Took me a bit to figure it out since i couldn't find an existing example code for it.

  • sorl-thumbnail
Read More

Template Tag of Django Image Thumb Creator

**You can save these codes into a templatetag file in your django app. Then use codes like these in your template files:** **************************************************************************** {% load *yourtags* %} ... <img src="{% thumb *yourmodel.picturefield* 200 300 0 %}"/> <img src="{% thumb *yourmodel.picturefield* 500 400 yes %}"/> ... The parameters are: imagefield ImageField width Integer height Integer rescale [1, yes, true, 0, no, false] **Some codes come from <djangosnippets.org>**

  • django
  • image
  • templatetag
  • thumb
Read More

Unique FileFiled or FileFiled with custom validation and overwriting files on update

I needed to overwrite files on update (not create new ones) but also a validation which would prevent to upload 2 files with the same name. The CustomCheckFiled triggers a validation passing the filename and model instance. If the validation returns false, the validation error_message will be displayed in admin. The OverwriteStorage is needed because the default storage alters the name if such name already exists. Enjoy.

  • validation
  • FileFiled
  • FileSystemStorage
  • overwrite
Read More

Run model validation before saving a model instance

How to validate your model at save using the pre_save signal. from http://groups.google.com/group/django-developers/browse_thread/thread/eb2f760e4c8d7911/482d8fd36fba4596?hl=en&lnk=gst&q=problem+with+Model.objects.create#482d8fd36fba4596

  • save
  • clean
  • pre_save
  • signals
  • validate
  • full-clean
  • full_clean
Read More

Drag and drop ordering of admin list elements for Grappelli

Adds drag-and-drop ordering of rows in the admin list view for [Grappelli](http://code.google.com/p/django-grappelli/). This is based on [Snippet #2057](http://djangosnippets.org/snippets/2057/) and fixes some bugs as well as switching to jQuery/jQuery UI provided by Grappelli. No additional files need to be installed. The model needs to have a field holding the position and that field has to be made list_editable in the ModelAdmin. The changes of the ordering are applied after clicking 'Save'.

  • admin
  • sort
  • jquery
  • order
  • sortable
  • grappelli
Read More