Login

Snippets by showell

Snippet List

Showell markup--DRY up your templates

The code shown implements a preprocessor for Django templates to support indentation-based syntax. The pre-markup language is called Showell Markup. It allows you to remove lots of close tags and random punctuation. It also has a syntax for cleaning up individual lines of HTML with a pipe syntax for clearly separating content from markup. You can read the docstrings to glean the interface. Here are examples: >> table >> tr >> td Right >> td Center >> td Left >> div class="spinnable" >> ul >> li id="item1" One >> li id="item2" Two %% extends 'base.html' %% load smartif %% block body %% for book in books {{ book }} %% if condition Display this %% elif condition Display that %% else %% include 'other.html' >> tr class="header_row" Original Author | th class="first_column" Commenters | th Title | th Action | th Last words | th By | th When | th >> ol class="boring_list" One | li Two | li Three | li {{ element4|join:',' }} | li Hello World! | b | span class="greeting" ; br Goodbye World! | i | span class="parting_words"; br ; hr >> p class="praise" Indentation-based syntax is so Pythonic! Archive LINK collection.archive referral.pk Home LINK home.home Friends LINK friendship.friends Create a card LINK referrals.create Recent changes LINK activity.recent_changes >> FORM referrals.create {{ form.as_p }} {{ referral.id } | HIDDEN referral

  • templates
  • dry
  • preprocessor
Read More

safe(r) monkeypatching scheme for django testing

In test code, it is sometimes useful to monkeypatch a Django method to have stubbed out behavior, so that you can simplify data setup. Even with decent data setup you might want to avoid execution of Django code that is not the target of your test. The code snippet shown here illustrates a technique to limit the scope of your monkeypatches. It uses the Python "with" statement, which was introduced in 2.5. [with statement](http://effbot.org/zone/python-with-statement.htm) The key aspect of the "with" machinery is that you can set up an __exit__ method that gets called even if the code inside the "with" raises an exception. This guarantees that your monkeypatch gets un-monkeyed before any other code gets called. I don't recommend monkeypatches in production, but if you HAVE to resort to a monkeypatch, I definitely advise using "with" to limit their scope. The examples on the left illustrate how to suppress versions of reverse() and timesince()--look at the import statements to see which ones I am talking about. Obviously, monkeypatching is not for the faint of the heart, as you need to be able to find the code to monkeypatch in Django source, and you need to be sure there aren't decorators at play.

  • testing
  • monkeypatch
Read More

Variable._resolve_lookup monkeypatch

There are times when you want to hook into the Variable class of django.template to get extra debugging, or even to change its behavior. The code shown is working code that does just that. You can monkeypatch template variable resolution by calling patch_resolver(). I recommend using it for automated tests at first. My particular version of _resolve_lookup does two things--it provides some simple tracing, and it also simplifies variable resolution. In particular, I do not allow index lookups on lists, since we never use that feature in our codebase, and I do not silently catch so many exceptions as the original version, since we want to err on the side of failure for tests. (If you want to do monkeypatching in production, you obviously want to be confident in your tests and have good error catching.) As far as tracing is concerned, right now I am doing very basic "print" statements, but once you have these hooks in place, you can do more exotic things like warn when the same object is being dereferenced too many times, or even build up a graph of object interrelationships. (I leave that as an exercise to the reader.) If you want to see what the core _resolve_lookup method looks like, you can find it in django/templates/__init__.py in your installation, or also here (scroll down to line 701 or so): [source](http://code.djangoproject.com/browser/django/trunk/django/template/__init__.py)

  • template
  • variable
  • resolve
Read More

sortby template tag

This is a variation on dictsort that assumes objects with attributes, not dictionaries. Example usage: {% for book in author.book_set.all|sortby:'title' %}

  • template
  • dictsort
Read More

elif for smart if tag

The code posted here adds "elif" functionality to the [smart if snippet 1350](http://www.djangosnippets.org/snippets/1350/). To use the snippet first follow the instructions for installing smart_if, then swap in the method shown on the left for the original smart_if method. You'll need to keep all the supporting classes from the original implementation, of course. You can use it like this: {% if 0 %} {% if 1 %} Hello Venus {% else %} unexpected {% endif %} {% elif 0 %} Hello Earth {% elif 0 %} Foo {% else %} Hello Mars {% endif %} The code is compatible with original smart_if classes as of June 2009, and the use of "__contains__" in the Enders class relies on the current implementation of Parser.parse, which says "if token.contents in parse_until:" in the one place it uses the parse_until parameter, which seems like stable code to me. The code works by recursively creating SmartIfNodes for the elif clauses.

  • template
  • smart_if
Read More

Template Context Debugger with Pydev

This snippet is a variation on snippet 1550 that works with the Eclipse pydev plugin. This allows you to set up a breakpoint anywhere in your template code, by simply writing {% pydev_debug %}. Be sure to launch pydev in debugger mode first. Once you're in the debugger, you can explore the stack and quickly find which context variables are set. This can be especially useful inside for loops, etc., where you want to see how the templating code is mucking with the context. This can also be useful when your templates are ultimately rendered by code that might not understand very well, such as generics.

  • template
  • debug
  • pydev
Read More

compressing polygons for geodjango

The code shown allows you, in GeoDjango, to reduce the number of points in your polygons. It helps reduce storage needs and makes queries run faster, at the cost of some precision. It provides a variation on the simplify() method that comes with the GEOS API, allowing you to specify a number of points instead of a distance tolerance. It is set up as a management command so that you can run it with python manage.py. See the django docs for how to set that up. The example shown assumes a table called CountyBorders with fields "name" and "mpoly." It should be straightforward to adapt it for your needs. Look at the first three lines of the simplify() method in particular for customization. The rest of the code is pretty generic, and it should run fast enough in a one-time batch process for most needs. The algorithm tries to keep the 75 points that provide the most definition for the shape. Each point in a polygon defines a triangle with its immediate neighbors. If that triangle has no area (the degenerate case), it is a midpoint on the segment between its neighbors and adds no value whatsoever. This principle is extended to say that the larger the triangle, the more value the point has in defining the shape. (You can find more refined algorithms, but this code seems to work fine by visual inspection.)

  • geodjango
  • polygons
Read More

make templates fail loudly in dev

Add the line shown, or something similar, to your settings/dev.py, so that you can more clearly see when django is silently hiding errors in your template tags.

  • template
  • debugging
Read More

testdata tag for templates

The "testdata" tag allows you to inline test data into your templates, similar in spirit to Python doctests. There are two sections--the test data and the actual template to be rendered. In non-test mode your template renders normally from whatever views call it, and there is very little overhead to skip over the test data section (happens at parse time). Here are the goals: 1. Provide convenient way to test templates without surrounding infrastructure. 2. Make templates be self-documenting in terms of expected data. 3. Allow insertion of test data at arbitrary places in template structure. Hello-world looks like this: {% load handytags %} {% testdata %} { 'greeting': 'Hello', 'planet': 'World', } {% --- %} {# This is where the actual template begins #} {{ greeting }} <b>{{ planet }}</b> {% endtestdata %} To invoke it, set up urls.py with something like this: url(r'^testdata/(?P<template_path>.*)', test_template) def test_template(request, template_path): context = {'testdata_use': True} # put request vars into context to help choose # which test data we want to render for field in request.GET: context[field] = request.GET[field] return render_with_request(template_path, context, request) Then call: http://127.0.0.1:8000/testdata/hello_world.html Features: 1. The testdata tag's rendering will expose missing variables a bit more aggressively than Django normally does. 2. You have the full power of the template language to set the test data (which ultimately gets eval'ed as a Python expression). 3. As mentioned above, the tag is mostly unobtrusive. Limitations/caveats: 1. Right now the only data format I support is pure Python, but the tag could be modified pretty easily to support JSON or YAML. 2. The VerboseContext class is pretty heavy-handed--I really just want a hook into Django to tell it to render a section with more strictness about variables. Suggestions welcome. 3. You can put the testdata tag pretty much anywhere, but the normal rules apply...for example, if you are in a template that has the extend tag, you'll want to put the testdata tag in individual blocks.

  • templates
  • testing
  • doctest
  • custom-template-tag
Read More

outliner template tag

Let's say you have a dataset and you want to render a page with sections/subsections/subsubsections down to some arbitrary depth and with arbitrary keys. For example, you might want to show cars broken out by year/price_range or price_range/year or price_range/manufacturer/model. The outliner template tag allows you to support multiple breakdowns of your data in a DRY sort of way. In order to use it, you supply four things: 1. a template for surrounding each subsection (think turtles all the way down) 2. a queryset (really anything iterable) 3. sectionizer dictionary/objects (see sample code, you must supply key_method) 4. inner html to render the lowest subsections The template provides the following: 1. It recursively uses each of your sectionizers' key methods to divvy up data sets. 2. It surrounds each section with templates of your choosing. 3. It renders the inner template for all the "leaf" elements of your tree. 4. It supplies some handy context vars for things like depth and outline ids. What this is not: 1. this is not for arbitrary tree data--think of the tree as fixed depth 2. this is not as simple as the regroup tag--if you have a concrete organization to your data, you should keep it simple and hand-code your templates

  • template
  • tree
  • outline
  • recursive
Read More

url extension mechanism

Executive summary: url "include" on steroids--granular extra parms and validate names in passing We maintain multiple Django applications, and we use the excellent built-in include mechanism to allow one urls.py to borrow from another: http://docs.djangoproject.com/en/dev/topics/http/urls/ If you scroll down to the section entitled "Passing extra options to include," you will see this annoying limitation: ''' Note that extra options will always be passed to every line in the included URLconf, regardless of whether the line's view actually accepts those options as valid. For this reason, this technique is only useful if you're certain that every view in the included URLconf accepts the extra options you're passing. ''' My snippet overcomes this limitation, allowing you to extend individual urls without polluting the namespace. The function also has the nice side effect of validating that the parent hasn't changed names on you.

  • url
  • extend
  • include
Read More

showell has posted 11 snippets.