Login

Most bookmarked snippets

Snippet List

Profiling Middlware

Displays hotshot profiling for any view. http://yoursite.com/yourview/?prof Add the "prof" key to query string by appending ?prof (or &prof=) and you'll see the profiling results in your browser. It's set up to only be available in django's debug mode, but you really shouldn't add this middleware to any production configuration. * Only tested on Linux * You should probably use this one instead: http://djangosnippets.org/snippets/2126/

  • middleware
  • profile
  • debug
  • stats
  • performance
  • hotshot
Read More

A couple of template filters for partitioning lists

People -- and by "people" I mean Jeff Croft -- often ask about how to split a list into multiple lists (usually for presenting as columns in a template). These template tags provide two different ways of splitting lists -- on "vertically", and the other "horizontally".

  • template
  • filter
  • lists
Read More

django-tagging clouds template tag

template tag for producing tag clouds for a given model, using django-tagging application: http://code.google.com/p/django-tagging/ Sample: http://skam.webfactional.com/tags/ Usage: {% tags_cloud_for_model articles.Article as object_list %} {% tags_cloud_for_model articles.Article as object_list step 6 %}

  • template
  • tag
  • tags
  • tagging
  • templatetags
  • clouds
Read More
Author: skam
  • 13
  • 59

Avoid widows using a template filter

**Support good typography! Avoid widows! ** "Widows" are single words that end up on their own line, thanks to automatic line-breaks. This is an no-no in graphic design, and is especially unsightly in headers and other short bursts of text. This filter automatically replaces the space before the last word of the passed value with a non-breaking space, ensuring there is always at least two words on any given line. Usage is like so: {{ blog.entry.headline|widont }} It's a simple tag, but good typography is one of the hallmarks of a well-designed site that separates it from amateurish counterparts. Note: The idea and name "widont" is copped directly from [Shaun Inman](http://shauninman.com), who wrote a [similar feature for WordPress](http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin).

  • filter
  • widows
  • templatetag
  • typography
  • shauninman
  • widont
Read More

Switch/case tags.

Meant mostly as a demo of how to do complex block tags, here's a switch/case implementation. It's deliberately simplistic: no default cases, no multiple values for the same case, etc. This is so that you can focus on the technique. Pay particular attention to how both switch and case pull out their child nodes and save them for later rendering. This is a very useful technique for these types of "structured" template tags.

  • templatetag
  • switch
  • case
  • flow
  • logic-doesnt-belong-in-templates
Read More

Unobtrusive comment moderation

**Before using this snippet**, please note that it's largely been superseded by [comment_utils](http://code.google.com/p/django-comment-utils/), which includes a more featureful and extensible version of this system, particularly with respect to additional moderation options and useful things like email notifications of comments. Once upon a time I hacked the copy of `django.contrib.comments` I'm using on my blog, so that I could have comments get set to `is_public=False` if posted more than 30 days after the entry's publication, and to add Akismet spam filtering. I've regretted it ever since, because it's made upgrading my copy of Django a pain. So here's an improved version which doesn't require hacking directly on Django. To use it, you'll need to do a few things: 1. Grab the [Python Akismet module](http://www.voidspace.org.uk/python/modules.shtml#akismet) and install it somewhere on your server. 2. In your settings file, add `AKISMET_API_KEY`, and make sure its value is a valid Akismet key. If you don't have an Akismet key, you can [get one at wordpress.com](http://wordpress.com/api-keys/). 3. Put this code -- both the function and the dispatcher calls -- somewhere in your project that's _guaranteed_ to be imported early (until this code is executed, the moderation function won't be set up to listen for comments posting). To have comments on a certain type of object (say, weblog entries) automatically go into moderation when the object reaches a certain age, define a method on that object's model called `comments_open`, and have it return `False` when comments should be auto-moderated.

  • akismet
  • comments
  • moderation
Read More

SSL Middleware

**SSL Middleware** This middleware answers the problem of redirecting to (and from) a SSL secured path by stating what paths should be secured in urls.py file. To secure a path, add the additional view_kwarg 'SSL':True to the view_kwargs. For example ` urlpatterns = patterns('some_site.some_app.views', (r'^test/secure/$','test_secure',{'SSL':True}), ) ` All paths where 'SSL':False or where the kwarg of 'SSL' is not specified are routed to an unsecure path. For example ` urlpatterns = patterns('some_site.some_app.views', (r'^test/unsecure1/$','test_unsecure',{'SSL':False}), (r'^test/unsecure2/$','test_unsecure'), ) ` **Gotcha's** Redirects should only occur during GETs; this is due to the fact that POST data will get lost in the redirect. **Benefits/Reasoning** A major benefit of this approach is that it allows you to secure django.contrib views and generic views without having to modify the base code or wrapping the view. This method is also better than the two alternative approaches of adding to the settings file or using a decorator. It is better than the tactic of creating a list of paths to secure in the settings file, because you DRY. You are also not forced to consider all paths in a single location. Instead you can address the security of a path in the urls file that it is resolved in. It is better than the tactic of using a @secure or @unsecure decorator, because it prevents decorator build up on your view methods. Having a bunch of decorators makes views cumbersome to read and looks pretty redundant. Also because the all views pass through the middleware you can specify the only secure paths and the remaining paths can be assumed to be unsecure and handled by the middleware. This package is inspired by Antonio Cavedoni's SSL Middleware Notes: Updated per Jay Parlar at http://www.djangosnippets.org/snippets/240/ - Added a test for the way webfaction handles forwarded SSL requests.

  • middleware
  • ssl
Read More

Super User Conditional Page Exception Reporting

**Step 1** Save somewhere in your project directory **Step 2** Add to your settings.py MIDDLEWARE_CLASSES = ( 'django.middleware.common.CommonMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.middleware.doc.XViewMiddleware', 'utils.debug.UserBasedExceptionMiddleware', ) Normal users will get your 500.html when debug = False, but If you are logged in as a super user then you get to see the stack trace in all its glory.

  • middleware
  • debug
  • exception
Read More

Using the {% widthratio %} template tag with CSS to create a bar graph

The {% widthratio %} template tag is under appreciated! Here, it's combined with CSS to create a bar graphic for the results of an election (this example comes from [this page](http://flickr.com/photos/postneo/405239750/in/photostream/), but has been modified slightly for simplicity's sake). The widthratio tag can be used to create all sorts of graphs and charts, as well as things like tag clouds. Here, we pass it the number of votes for a candidate, the total number of votes in the election, and the integer 190, which is the width, in pixels, of a "full" bar on the bar graph. In other words, 100% = 190 pixels. It works great!

  • template
  • templatetag
  • widthratio
  • graph
  • infographic
Read More

RequestFactory: Easily create mock request objects, for use in testing

Django's testing framework assumes you will be running your tests against "live" views that have been plugged in to your site's URL configuration - but sometimes you might want to run a test against a view function without first wiring it in to the rest of the site. This class makes it easy to do that by providing a "factory" for creating mock request objects, re-using the existing test Client interface (and most of the code). Once you've created a request object in your test you can use it to call your view functions directly, then run assertions against the response object that gets returned.

  • testing
  • httprequest
Read More

DebugFooter middleware

Adds a hidden footer to the bottom of every text/html page containing a list of SQL queries executed and templates that were loaded (including their full filesystem path to help debug complex template loading scenarios). To use, drop in to a file called 'debug_middleware.py' on your Python path and add 'debug_middleware.DebugFooter' to your MIDDLEWARE_CLASSES setting.

  • sql
  • middleware
  • debugging
Read More

Datetime widget

This widget uses: [DHTML Calendar Widget](http://www.dynarch.com/projects/calendar/). It is very simple implementation but may be easily extended/changed/refined. 1. Necessary files: First download calendar package and extract it to your MEDIA folder (MEDIA/calendar/...) You'll also need a small gif that will be shown as a button that allows user to display calendar. By default this 'gif' is searched at '[MEDIA]images/calbutton.gif' but you may change this path in the code (calbtn variable). You need to download or create callbutton.gif image by yourself (it is not included). 2. Include css and js files in your page (as shown in the comment in the code). 3. In form code assign a widget to a field as usual (see newforms documentation for more details). 4. It is possible to change date format by specifying different value for 'dformat' attribute of widget class. If you get javascript errors while trying to open calendar try to use english translation file (calendar-en.js). I've found that some translations, eg. Polish, are broken by default. In this case you should override your language translation with english one and translate it by yourself (it is easy).

  • datetime
  • date
  • calendar
  • widget
  • dhtml
Read More

Send large files through Django, and how to generate Zip files

This snippet demonstrates how you can send a file (or file-like object) through Django without having to load the whole thing into memory. The FileWrapper will turn the file-like object into an iterator for chunks of 8KB. This is a full working example. Start a new app, save this snippet as views.py, and add the views to your URLconf. The send_file view will serve the source code of this file as a plaintext document, and the send_zipfile view will generate a Zip file with 10 copies of it. Use this solution for dynamic content only, or if you need password protection with Django's user accounts. Remember that you should serve static files directly through your web server, not through Django: http://www.djangoproject.com/documentation/modpython/#serving-media-files

  • sendfile
  • zipfile
  • tempfile
  • temporaryfile
  • filewrapper
Read More

ExcelResponse

A subclass of `HttpResponse` which will transform a `QuerySet`, or sequence of sequences, into either an Excel spreadsheet or CSV file formatted for Excel, depending on the amount of data. All of this is done in-memory and on-the-fly, with no disk writes, thanks to the StringIO library. **Requires:** [xlwt](http://pypi.python.org/pypi/xlwt/) **Example:** def excelview(request): objs = SomeModel.objects.all() return ExcelResponse(objs)

  • csv
  • output
  • httpresponse
  • excel
Read More

3109 snippets posted so far.