Login

All snippets written in Python

Snippet List

CompressedTextField

A CompressedTextField to transparently save data gzipped in the database and uncompress at retrieval. Full description at my blog: [arnebrodowski.de/...Field-for-Django.html](http://www.arnebrodowski.de/blog/435-Implementing-a-CompressedTextField-for-Django.html)

  • text
  • model
  • field
  • compressed
Read More

duplicate model object merging script

Use this function to merge model objects (i.e. Users, Organizations, Polls, Etc.) and migrate all of the related fields from the alias objects the primary object. Usage: from django.contrib.auth.models import User primary_user = User.objects.get(email='[email protected]') duplicate_user = User.objects.get(email='[email protected]') merge_model_objects(primary_user, duplicate_user)

  • django
  • fields
  • model
  • generic
  • related
  • merge
  • duplicates
  • genericforeignkey
Read More

typygmentdown

Based heavily on [snippet #119](/snippets/119/), this is an all-in-one function which applies Markdown and typogrify, and adds Pygments highlighting (selected from a class name or by having Pygments guess the language) to any `<code>` elements found in the text. It also adds some niceties for picking up useful arguments to Markdown and Pygments, and registers itself as a markup filter with the `template_utils` formatter. Requirements: * [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/) * [Pygments](http://pygments.org/) * [python-markdown](http://www.freewisdom.org/projects/python-markdown/) * [template_utils](http://code.google.com/p/django-template-utils/) * [typogrify](http://code.google.com/p/typogrify/)

  • pygments
  • markup
  • markdown
  • typogrify
Read More

extras.py for management commands

! Note - no longer needed Save this script in the same directory as manage.py and run it through the command line. It picks up project Command class instances. Something that will hopefully be fixed in the Django SVN version soon. Heres an example of a command: #utils/management/commands/sqlallall.py from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import models class Command(BaseCommand): help = "Returns sqlall for all installed apps." def handle(self, *args, **options): """ Returns sqlall for all installed apps. """ for app in models.get_apps(): call_command("sqlall", app.__name__.split(".")[-2])

  • management
  • commands
Read More

in_list filter

which you would use like this: The item is {% if item|in_list:list %} in list {% else %} not in list {% endif %}

  • template
  • filter
  • lists
  • tag
  • contains
  • in
Read More

paginator using url tag

Example for provided django-tagging url snippet: {% paginator 4 image_tag_paged tag=tag page %} links then equals {% url image_tag_paged tag=tag,page=n %}

  • tag
  • pagination
  • url
  • paginator
Read More

JSONField

This is a great way to pack extra data into a model object, where the structure is dynamic, and not relational. For instance, if you wanted to store a list of dictionaries. The data won't be classically searchable, but you can define pretty much any data construct you'd like, as long as it is JSON-serializable. It's especially useful in a JSON heavy application or one that deals with a lot of javascript. **Example** (models.py): from django.db import models from jsonfield import JSONField class Sequence(models.Model): name = models.CharField(maxlength=25) list = JSONField() **Example** (shell): fib = Sequence(name='Fibonacci') fib.list = [0, 1, 1, 2, 3, 5, 8] fib.save() fib = Sequence.objects.get(name='Fibonacci') fib.list.append(13) print fib.list [0, 1, 1, 2, 3, 5, 8, 13] fib.get_list_json() "[0, 1, 1, 2, 3, 5, 8, 13]" *Note:* You can only save JSON-serializable data. Also, dates will be converted to string-timestamps, because I don't really know what better to do with them. Finally, I'm not sure how to interact with forms yet, so that realm is a bit murky.

  • models
  • model
  • json
  • db
  • field
  • json-field
Read More

If modulo template tag

Usage: {% ifmodulo forloop.counter 4 0 %} <!-- do something --> {% else %} <!-- do something else --> {% endifmodulo %} or {% ifnotmodulo 5 3 %} <!-- do something --> {% else %} <!-- do something else --> {% endifmodulo %} When the third parameter does not exist, it is assumed you're checking for values different than 0.

  • template
  • tag
  • if
  • modulo
Read More

cron/console bootstrap django

Call this function as the first thing in your cron, or console script; it will bootstrap Django, and allow you to access all of the Django modules from the console, with out using 'python manage.py shell' Examples: # A script within your django project. from django_bootstrap import bootstrap bootstrap(__file__) --- or --- # A cron script located outside of your django project from django_bootstrap import bootstrap bootstrap("/path/to/your/project/root/")

  • django
  • console
  • cron
  • bootstrap
Read More

page_link

To make page links like below: Prev 1 ... 23 24 25 26 27 ...221 Next Use like this , "bbs_posting_list" is the name of url {% page_link "bbs_posting_list" page pages %}

  • page
Read More

Template tag to sort a list of links

Sorts a list of HTML anchor tags based on the anchor's contents. This is useful, for example, when combining a static list of links with a dynamic list that needs to be sorted alphabetically. It ignores all attributes of the HTML anchor. {% load anchorsort %} {% anchorsort %} <a href="afoo.jpg">Trip to Fiji</a> <a href="bfoo.jpg">Doe, a deer, a female deer!</a> {% for link in links %} <a class="extra" href="{{ link.href|escape }}">{{ link.name|escape }}</a> {% endfor %} {% endanchorsort %} Note that case (capital vs. lower) is ignored. Any HTMl within the node itself **will not be removed**, so sorting `<a>Bar</a><a><strong>Foo</strong><a/>` will sort as `<a><strong>Foo</strong></a><a>Bar</a>` because `<` is logically less than `b`.

  • template
  • sort
  • anchor
  • a
Read More

I18n URLs via Middleware

This is an example middleware that is highly inspired by how Symfony handles [i18n in URLs](http://www.symfony-project.com/book/trunk/13-I18n-and-L10n#Changing the Culture for a User). You basically set a (?P<dj_culture>[\w-]+) pattern in your URL and this middleware will determine the language to use for the i18n toolkit for Django. It also removes the dj_culture parameter after dealing with it, so that you don't have to change all the views you want this middleware to work with.

  • middleware
  • i18n
  • url
Read More

Yet another SQL debugging facility

Inspired by http://www.djangosnippets.org/snippets/159/ This context processor provides a new variable {{ sqldebug }}, which can be used as follows: {% if sqldebug %}...{% endif %} {% if sqldebug.enabled %}...{% endif %} This checks settings.SQL_DEBUG and settings.DEBUG. Both need to be True, otherwise the above will evaluate to False and sql debugging is considered to be disabled. {{ sqldebug }} This prints basic information like total number of queries and total time. {{ sqldebug.time }}, {{ sqldebug.queries.count }} Both pieces of data can be accessed manually as well. {{ sqldebug.queries }} Lists all queries as LI elements. {% for q in sqldebug.queries %} <li>{{ q.time }}: {{ q }}</li> {% endfor %} Queries can be iterated as well. The query is automatically escaped and contains <wbr> tags to improve display of long queries. You can use {{ q.sql }} to access the unmodified, raw query string. Here's a more complex example. It the snippet from: http://www.djangosnippets.org/snippets/93/ adjusted for this context processor. {% if sqldebug %} <div id="debug"> <p> {{ sqldebug.queries.count }} Quer{{ sqldebug.queries|pluralize:"y,ies" }}, {{ sqldebug.time }} seconds {% ifnotequal sql_queries|length 0 %} (<span style="cursor: pointer;" onclick="var s=document.getElementById('debugQueryTable').style;s.display=s.display=='none'?'':'none';this.innerHTML=this.innerHTML=='Show'?'Hide':'Show';">Show</span>) {% endifnotequal %} </p> <table id="debugQueryTable" style="display: none;"> <col width="1"></col> <col></col> <col width="1"></col> <thead> <tr> <th scope="col">#</th> <th scope="col">SQL</th> <th scope="col">Time</th> </tr> </thead> <tbody> {% for query in sqldebug.queries %}<tr class="{% cycle odd,even %}"> <td>{{ forloop.counter }}</td> <td>{{ query }}</td> <td>{{ query.time }}</td> </tr>{% endfor %} </tbody> </table> </div> {% endif %}

  • sql
  • debug
  • queries
  • db
  • database
  • contextprocessor
Read More

2956 snippets posted so far.