Login

Top-rated snippets

Snippet List

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

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

render_to_response wrapper

Simplifies using RequestContext in render_to_response. Simply call the wrapper with request as the first argument, and the rest of the arguments are as normal for render_to_response. ex: render_response(request, 'foo_list.html', {'foo': Foo.objects.all()})

  • render_to_response
  • requestcontext
  • shortcut
  • template
Read More

Capture template output as a variable

Tags like `url` and `trans` provide no way to get the result as a context variable. But how would you get a computed URL into a `blocktrans`? This snippet solves the general problem. Just put the template code whose output you want to capture within `captureas` tags. For example: {% captureas login_url %}{% url login %}{% endcaptureas %} {% blocktrans %} <a href="{{login_url}}">login</a> {%endblocktrans%}

  • template
  • variable
  • assign
  • capture
  • blocktrans
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

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

Dynamically adding forms to a formset with jQuery

I recently worked on an application, where I had to provide a way for users to search for objects based on user-defined properties attached to these objects. I decided to model the search form using a formset, and I thought it'd be a good idea to allow users dynamically add and remove search criteria. The script (dynamic-formset.js) should be re-usable as-is: 1. Include it in your template (don't forget to include jquery.js first!). 2. Apply the 'dynamic-form' class to the container for each form instance (in this example, the 'tr'). 3. Handle the 'click' event for your `add` and `delete` buttons. Call the `addForm` and `deleteForm` functions respectively, passing each function a reference to the button raising the event, and the formset prefix. That's about it. In your view, you can instantiate the formset, and access your forms as usual.

  • newforms
  • jquery
  • dynamic-formset
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

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

ExprTag - Calculating python expression and saving the result to a variable

This tag can be used to calculate a python expression, and save it into a template variable which you can reuse later or directly output to template. So if the default django tag can not be suit for your need, you can use it. How to use it {% expr "1" as var1 %} {% expr [0, 1, 2] as var2 %} {% expr _('Menu') as var3 %} {% expr var1 + "abc" as var4 %} ... {{ var1 }} for 0.2 version {% expr 3 %} {% expr "".join(["a", "b", "c"]) %} Will directly output the result to template Syntax {% expr python_expression as variable_name %} python_expression can be valid python expression, and you can even use _() to translate a string. Expr tag also can used context variables.

  • tag
Read More

Generate newforms-admin admin.py file

This is a utility script that scans a models.py file and automatically outputs the corresponding newforms-admin source code - the code that goes into the admin.py file. The purpose is to simplify the migration to newforms-admin. Here is what it outputs: * an import line that lists only the needed classes from the model. * inline editing classes - inheriting from either `admin.TabularInline` or `admin.StackedInline` * admin options classes containing any original `Admin` class contents (`'fields'` is replaced by `'fieldsets'` and the value of `'classes'` is made into a tuple), plus the following fields whose values are determined automatically: `inlines`, `prepopulated_fields`, `filter_horizontal`, `filter_vertical` and `raw_id_fields` * invokations of `admin.site.register` for the generated admin options classes. Example usage of the script (this will generate the admin.py file for the models.py file in the satchmo.product module): >./new-forms-gen.py satchmo.product > admin.py

  • newforms-admin
Read More
Author: NL
  • 16
  • 21

Plugin Framework

This is a very basic -- yet fully functional -- framework for producing a loosely coupled plugin architecture. Full details of its use can be found [on my blog](http://gulopine.gamemusic.org/2008/jan/10/simple-plugin-framework/), but the basics are listed below. ## Defining a mount point for plugins class ActionProvider: __metaclass__ = PluginMount ## Implementing plugins class Insert(ActionProvider): def perform(self): # Do stuff here class Update(ActionProvider): def perform(self): # Do stuff here ## Utilizing plugins for action in ActionProvider.plugins: action.perform() Yes, it really is that simple.

  • plugins
Read More

3110 snippets posted so far.