Login

All snippets written in Python

2956 snippets

Snippet List

Django using admin horizontal filter in forms

This snippet uses the admin FilterSelectMultiple widget in normal forms. Earlier I tried this without the **internationalization javascript** and failed, so I looked around the web and found couple of posts, they worked but suggest many customizations. I learnt from them that they had this *jsi18n* javascript included. I included it with mine and it worked. I have written a [detailed post](http://www.rohanjain.in/coding/2011/06/20/django-using-admin-horizontal-filter-in-forms/) about this.

  • admin
  • forms
  • widget
Read More

filter for extracting a number of paragraphs from any HTML code

From: [incredible times](http://incredibletimes.org) With inspiration from: [Unethical Blogger](http://unethicalblogger.com/2008/05/03/parsing-html-with-python.html) This code parses any provided HTML content, and extracts a number of paragraphs specified, with all the content and tags inside them. Example: Template variable "content" contains: <a href="#>some text</a> <p><strong>Testing</strong>testing testing this is a tester's life</p> <div>I wont see the world</div> <p>Another paragraph</p> So, place this code in any loaded template module (inside a templatetags folder of your app... i.e. myapp/templatetags/myutils.py) {% load myutils %} {{ content|paragraphs:"1"}} Would return: <p><strong>Testing</strong>testing testing this is a tester's life</p> Whereas {% load myutils %} {{ content|paragraphs:"2"}} Returns: <p><strong>Testing</strong>testing testing this is a tester's life</p> <p>Another paragraph</p>

  • filter
  • paragraph
  • html
  • parse
  • extract
Read More

A slightly better YAML serializer

I find Django's default YAML serializer output too repetitive, so I came up with this customized version that avoids outputting the model name for every single object, and makes the primary key into an index for the object's fields. This allows many simple model instances to be serialized as one-liners. See the module docstring for additional explanation and usage notes.

  • yaml
  • serializer
  • deserializer
Read More

Django Dictionary Model

This is a model that implements (most of) the python dictionary interface. Meaning, you can work with this model exactly like a python dictionary, and it handles querying the database for it's values, saving/deleting the helper objects, etc. I wrote this originally when I needed to store an arbitrary dictionary in the database, and decided to work it up into a near-complete implementation of a dictionary. In order to make sure that the dictionary is the most optimized possible, I have a static method that can be used for retrieval. Feel free to ignore it if you don't care about optimizing database queries. Here's an example: Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from binder.models import Dictionary >>> d = Dictionary.getDict('Foobar') >>> print d {u'Foobar': u'omgbbq', u'HAHAHAH': u"who's afraid of a big, black, bat?"} >>> d['pot'] = 'The kettle is black.' >>> print d {u'Foobar': u'omgbbq', u'pot': u'The kettle is black.', u'HAHAHAH': u"who's afraid of a big, black, bat?"} >>> print d['pot'] The kettle is black. >>> for k, v in d.iteritems(): ... print k +":", v ... Foobar: omgbbq HAHAHAH: who's afraid of a big, black, bat? pot: The kettle is black. >>> print d.keys() [u'Foobar', u'HAHAHAH', u'pot'] >>> print d.values() [u'omgbbq', u"who's afraid of a big, black, bat?", u'The kettle is black.'] >>> There's several more functions that I've implemented; check the code to see. (An interesting note: DictField saves immediately upon making a change, which is good to keep in mind in case that functionality isn't expected.) Hope someone finds this useful. :) --Chris

  • model
  • python
  • dict
  • dictionary
Read More

Generic object_detail view filterable by multiple url values

This view acts as an extension to the object_detail generic view in django.views.generic.object_list. The standard generic view can only filter the queryset by object_id or slug; this view allows you to filter by any parameter you like, as well as multiple parameters. The usage is the same as the standard object_detail view except that you must also give the parameter 'filters', which should be an array of what you would like to filter the url values as, and instead of 'slug' or 'object_id' as the regex parameter in the URL, use 'value1', 'value2', etc. Example: If you have a list of companies, each with multiple branches, you may want a branch details page. A URL for this may look as follows: http://www.mysite.com/company/company-slug/branch-slug/. To implement this simply use the urlpattern example give,

  • filter
  • urls
  • generic-views
  • generic-view
  • filterable
Read More

Gmail date format

Short and sweet date format from Gmail. Use as {{ message.sent_at|humantime }} Works for future dates too.

  • date
  • format
  • gmail
  • google mail
  • dateformat
Read More

Pygmentify a code using template filter

The above snippet can be added as a custom filter for rendering code snippets in django templates. A simple '|render' next to any source code will do. To add css, use the following command to generate css file. pygmentize -S emacs -f html > pygments-colorful.css And link this css file to the template.

  • template
  • django
  • pygments
  • custom-filters
Read More

Other translation block

Use in a with statement to set the translation to another locale for a block >>> from django.utils.translation import ugettext >>> ugettext('title') u'title' >>> with Translation('fr') as locale: ...: print locale.locale ...: print ugettext('title') ...: ...: fr titre >>> ugettext('title') u'title'

  • i18n
  • mail
  • translation
Read More

JSON Decimal encoder

Python json module or simplejson don't support Decimals out of the box. Here's an encoder that casts Decimals into floats and then displays them in desired format.

  • json
  • decimal
  • encoder
Read More

(Almost) Single table polymorphism in Django

An emulation of "table per hierarchy" a.k.a. "single table inheritance" in Django. The base class must hold all the fields. It's subclasses are not allowed to contain any additional fields and optimally they should be proxies. They however may provide additional methods to operate on the declared field. The presented solution supports implicit inheritance, even across ForeignKeys, and ManyToManyFields. No additional database hits are imposed.

  • django
  • django-models
  • table-per-hierarchy
  • single-table-polymorphism
  • polymorphism
Read More

Debug middleware for displaying sql queries and template loading info when ?debug=true

Originally based on: [http://djangosnippets.org/snippets/1872/](http://djangosnippets.org/snippets/1872/) The way the original snippet formatted sql didn't work for mysql properly so I taught it to use the sqlparse python module. Now it looks like this when settings.DEBUG=True: SQL executed: SELECT "django_session"."session_key", "django_session"."session_data", "django_session"."expire_date" FROM "django_session" WHERE ("django_session"."session_key" = d326108d313a2e5c5fb417364b005ab9 AND "django_session"."expire_date" > 2011-04-08 14:54:13.969881) took 0.001 seconds SELECT "auth_user"."id", "auth_user"."username", "auth_user"."first_name", "auth_user"."last_name", "auth_user"."email", "auth_user"."password", "auth_user"."is_staff", "auth_user"."is_active", "auth_user"."is_superuser", "auth_user"."last_login", "auth_user"."date_joined" FROM "auth_user" WHERE "auth_user"."id" = 2 took 0.000 seconds Additionally, this middlware is enabled conditionally based upon the url query string "debug". You can enable it for a single request by appending: ?debug=true to the url.

  • middleware
  • development
  • debug
Read More

collectstatic for media folders

Note: This concerns django 1.3 but the tags does not yet exist. We have a couple of apps, including 3rd party apps, that have the 'static' files in 'media' dirs. These files aren't found with collectstatic in django 1.3. With this snippet they will be. To use it: * paste the code in a file e.g. yourproject/finders.py. * include the finder in settings.STATICFILES_FINDERS: STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'yourproject.finders.AppMediaDirectoriesFinder', ) * ./manage.py collectstatic -n -l

  • media
  • staticfiles
Read More