Login

All snippets

Snippet List

Template tag for stripping blank lines

When writing clean and easy-to-read templates, it's usually good to have structural template tags (e.g. {%for%}, {%if%}) alone on their own line with proper indentation. When such a template is rendered, the resulting HTML will have blank lines in place of the template tags. The leading blank space used for indentation is also intact. This template tag strips all empty and all-whitespace lines when rendering the template. Be careful not to apply it when not intended, e.g. when empty lines are wanted inside PRE tags.

  • template
  • html
  • strip
  • empty
  • blank
Read More

Admin list_display Ajax

Sometimes it can be time consuming to go through a bunch of objects in Django's Admin if you only need to update one field in each. An example of this is an `order` field that allows you to manually set the order for a queryset. **This snippet contains examples of how to set up the Admin list_display to make Ajax calls to a custom view.** The following code may not be worthy of being a snippet, it's all pretty straightforward, but here it is for those who just want to copy-and-paste.

  • admin
  • jquery
Read More

require XMLHttpRequest view decorator

Decorator to make a view only accept requests from AJAX calls. Usage:: @require_xhr() def my_view(request): # Returns data # ... by [skam](http://skam.webfactional.com/)

  • ajax
  • views
  • view
  • decorator
  • decorators
  • xhr
  • xmlhttprequest
Read More

Zope testing django layer

[zope.testing](http://pypi.python.org/pypi/zope.testing/) is a test framework and test runner, similar to the django test runner and nose. This snippet is a [Layer](http://pypi.python.org/pypi/zope.testing/3.5.1#layers) class which you can assign as a layer attribute of your test suite to initialise and clean up the django test environment appropriately and to reset the test database between tests. for example: tests/suite.py import unittest from zope.testing import doctest def test_suite(): suite = doctest.DocFileSuite("models.txt") suite.layer = DjangoLayer return suite runtests.py import os from zope.testing import testrunner os.environ['DJANGO_SETTINGS_MODULE'] = 'project.settings' defaults = [ '--path', 'tests', '--tests-pattern', '^suite$', '-c' ] testrunner.run(defaults)

  • testing
  • tests
  • test
  • zope.testing
Read More

OpenID Form Field

**This is a newforms field for OpenID 1 & 2.** It normalizes and validates OpenID identifiers according to the [spec](http://openid.net/specs/openid-authentication-2_0.html#normalization): * `xri://=joelwatts` to `=joelwatts` * `joelwatts.com` to `http://joelwatts.com/` * `www.joelwatts.com` to `http://joelwatts.com/` An identifier that is well-formed, but not an OpenID (e.g. `example.com`), will cause a validation error. Requires [Python OpenID Library](http://openidenabled.com/python-openid/) 2.x.x.

  • newforms
  • fields
  • forms
  • form
  • field
  • openid
  • openid2
  • inames
  • identity
Read More

Unobtrusvie Foldable Admin Interface

Inspired by [snippet 550](http://www.djangosnippets.org/snippets/550/), this allows you to expand or collapse apps in the main Admin screen. Requires jQuery. If jquery.cookie.js is available it will remember which apps you have expanded. Recommended usage: Place the JavaScript in a file called `admin-expand.js`. Create `templates/admin/base_site.html` in your templates directory (which is also a good place to [brand your Admin](http://djangobook.com/en/1.0/chapter06/#cn70)). Put the following code near the top, and you're done (adjusting file paths as needed). {% extends "admin/base.html" %} {% block extrahead %} <script type="text/javascript" src="jquery-latest.js"></script> <script type="text/javascript" src="jquery.cookie.js"></script> <script type="text/javascript" src="admin-expand.js"></script> {% endblock %}

  • admin
  • jquery
Read More

Custom managers with chainable filters

The Django docs show us how to give models a custom manager. Unfortunately, filter methods defined this way cannot be chained to each other or to standard queryset filters. Try it: class NewsManager(models.Manager): def live(self): return self.filter(state='published') def interesting(self): return self.filter(interesting=True) >>> NewsManager().live().interesting() AttributeError: '_QuerySet' object has no attribute 'interesting' So, instead of adding our new filters to the custom manager, we add them to a custom queryset. But we still want to be able to access them as methods of the manager. We could add stub methods on the manager for each new filter, calling the corresponding method on the queryset - but that would be a blatant DRY violation. A custom `__getattr__` method on the manager takes care of that problem. And now we can do: >>> NewsManager().live().interesting() [<NewsItem: ...>]

  • manager
  • queryset
Read More

Cached lookup model mixin

This mixin is intended for small lookup-style models that contain mostly static data and referenced by foreign keys from many other places. A good example is a list of Payment options in an e-shop that is referenced from Orders and is hitting database `order.payment` at least one time for an order. The idea is to cache entire table in a dict in memory that will live for entire life of a whole process serving many requests. The downside is that you need to restart the server when a cached lookup table changes.

  • foreignkey
  • cache
  • lookup
  • parent
Read More

Auto rendering decorator with options

This view decorator renders automaticaly the template with the context provided both by the view "return" statement. For example: @auto_render def my_view(request): ... return 'base.html', locals() You can still return HttpResponse and HttpResponseRedirect objects without any problems. If you use Ajax requests, this decorator is even more useful. Imagine this layout: def aggregating_view(request): ... context = locals() partial1 = partial_view_1(request, only_context=True) partial2 = partial_view_2(request, only_context=True) # aggregate template include partial templates return 'aggregate.htmt', context.update(partial1).update(partial2) def partial_view_1(request): ... return 'partial_1.html', locals() def partial_view_2(request): ... return 'partial_2.html', locals() This way you can render you view individualy for specific ajax calls and also get their context for the aggregating view.

  • render_to_response
  • ajax
  • decorator
  • rendering
Read More

Age - custom filter

Based on the discussion at Empty Thoughts (http://blog.michaeltrier.com/2007/8/6/age-in-years-calculation) I built a quick and dirty custom filter. Save this as a file in your "templatetags" folder. I called mine "calculate_age.py" and then in your template "{% load calculate_age %}" then use it, "{{ object.birthdate|age }}"

  • filter
  • age
  • birthday
  • custom-tag
Read More

htmlentities

The built-in escape filter only works with certain characters. It works great in environments where you can declare your charset (UTF-8). However, not everything can handle anything outside of the ASCII charset. This replaces all non-ASCII characters with their encoded value as `&#174;` for ®, for example.

  • escape
  • htmlentities
  • ascii
Read More

SQLLoggerMidleware + infobar

This middleware will add a log of the SQL queries executed at the top of every page, in the form of an IE-like 'infobar'. It also includes a query count and total and per-query execution times. This snippet is based on snippet #344 "SQL Log Middleware + duplicates" by guettli. I did some adjustments to the code, to also add support for the application/xhtml+xml mime type, aswell as add the code for the infobar. Need DEBUG on, aswell as DEBUG_SQL, should not be used on production sites. It also expects a 16x16 png image called infobar_icon.png, which it is looking for in the /media/images folder (or /static/images, depending on your MEDIA_URL setting). I used a little light bulb icon from the Tango icon set, but am unable to attach the image. Any 16x16 png will do off course. Update 0.1.1: In the initial version of this middleware, the path to /media/images was hard-coded, and you had to adjust this middleware accordingly. Now, it correctly uses the MEDIA_URL setting from your settings.py file, so you no longer have to edit this middleware. 0.1.2: Made some adjustments to the CSS to get rid of a padding bug when the bar was displayed on a Django error page. Also if a page contains no queries, it won't bother printing an 'empty' table, with just column headers. 0.1.3: More tweaks to the CSS, odd/even row shading on queries table. 0.1.4: More CSS tweaks again 0.1.5: Minor tweaks 0.1.6: Sorry, I just realised that after some time, this snippet broke in the latest SVN of Django with a Unicode error, as arthur78 mentioned. I have managed to fix it, by wrapping line 258 and 259 in an str() function.

  • sql
  • middleware
  • logger
Read More

3110 snippets posted so far.