Login

All snippets written in Python

Snippet List

Safe template decorator

A decorator that restricts the tags and filters available to template loading and parsing within a function. This is mainly meant to be used when granting users the power of the DTL. You obviously don't want users to be able to do things that could be potentially malicious. The {% ssi %} tag, for example, could be used to display sensitive data if improperly configured. {% load %} gives them access to all the unlimited python code you wrote in your templatetags. {% load sudo %}{% sudo rm -rf / %} o_0 Note that the "load" tag (among others) is not listed in the default tag whitelist. If you parse a template (however indirectly) in a function decorated with this, unlisted builtin tags will behave like undefined tags (ie, they will result in a TemplateSyntaxError). Since {% load %} is not whitelisted, you may want to include some custom tags or filters as "builtins" for convenience. Simply put the module paths to the libraries to include in the `extra` kwarg or the `extra_libraries` list. Generally, this is not recommended, as these libraries need to be carefully and defensively programmed. **NOTE**: This **does not** do anything about cleaning your rendering context! That's completely up to you! This merely restricts what tags and filters are allowed in the templates. Examples: from django.template.loader import get_template safe_get_template = use_safe_templates(get_template) tmpl = safe_get_template('myapp/some_template.html') from django.template import Template use_safe_templates(Template)('{% load sudo %}') # TemplateSyntaxError: Invalid block tag 'load'

  • template
  • clean
  • safe
  • restrict
Read More

Binding signals to abstract models

Intro ----- I found a question on SO for which Justin Lilly's answer was correct but not as thorough as I'd like, so I ended up working on a simple snippet that shows how to bind signals at runtime, which is nifty when you want to bind signals to an abstract class. Bonus: simple cache invalidation! Question -------- [How do I use Django signals with an abstract model?](http://stackoverflow.com/questions/2692551/how-do-i-use-django-signals-with-an-abstract-model) I have an abstract model that keeps an on-disk cache. When I delete the model, I need it to delete the cache. I want this to happen for every derived model as well. If I connect the signal specifying the abstract model, this does not propagate to the derived models: pre_delete.connect(clear_cache, sender=MyAbstractModel, weak=False) If I try to connect the signal in an init, where I can get the derived class name, it works, but I'm afraid it will attempt to clear the cache as many times as I've initialized a derived model, not just once. Where should I connect the signal? Answer ------ I've created a custom manager that binds a post_save signal to every child of a class, be it abstract or not. This is a one-off, poorly tested code, so beware! It works so far, though. In this example, we allow an abstract model to define CachedModelManager as a manager, which then extends basic caching functionality to the model and its children. It allows you to define a list of volatile keys that should be deleted upon every save (hence the post_save signal) and adds a couple of helper functions to generate cache keys, as well as retrieving, setting and deleting keys. This of course assumes you have a cache backend setup and working properly.

  • managers
  • models
  • cache
  • model
  • manager
  • signals
  • abstract
  • signal
  • contribute_to_class
Read More

Debug SQL Query in Template

before this works, you'll need to satisfy all the criteria for getting debug information in your template context: Have 'django.core.context_processors.debug' in your TEMPLATE_CONTEXT_PROCESSORS setting (it was there in the default settings, last time I checked). Have your current IP in your INTERNAL_IPS setting. Use RequestContext when rendering the current template (if you're using a generic view, you're already using RequestContext). [Manuale Django](http://www.darioagliottone.it/django-guida/)

  • sql
  • template
  • debug
  • debugging
  • sql_queries
Read More

True Unique Boolean Model Decorator

This class decorator will help you when you want to keep a unique boolean (think a 'default' field which should only be only one set to true in a group). The interesting thing with this, is that it's possible to assign a subset of fields to be used, so that the uniqueness of the field will be guaranteed among only the subset (look at the Example section in the code to understand this behaviour). This is a better and improved way of doing http://djangosnippets.org/snippets/2676/

  • model
  • unique
  • boolean
Read More

Load response.content in browser (for debugging)

When debugging tests you frequently need to inspect response content, making a pdb. set_trace() breakpoint and printing response.content but html isn't enough human readable (even for programmers :D) so, why not open it in your browser? Suposse you save this code in utils.py and you break your testcase as this: response = self.client.get(self.url) import pdb; pdb.set_trace() Then: (pdb) from utils import load_response_on_firefox (pdb) load_response_on_firefox(response) Ta-Da!

  • debug
  • testing
  • response
  • response.content
Read More

REMOVE IMAGEFIELD ATTACHMENT IN DJANGO

File cleanup callback used to emulate the old delete behavior using signals. Initially django deleted linked files when an object containing a File/ImageField was deleted. Usage: >>> from django.db.models.signals import post_delete >>> post_delete.connect(file_cleanup, sender=MyModel, dispatch_uid="mymodel.file_cleanup")

  • filefield
Read More

DisableableSelectWidget

A Select widget that allows choices to be disabled. Specify `disabled_choices` to indicate which choices should be present in the list, but disabled. A possible use case for this is a form that displays data that can be edited by privileged user's but only viewed by others.

  • form
  • select
  • widget
Read More

Django-pagination with Bootstrap CSS

A quick django-pagination template fix to make it work with Bootstrap CSS Library 2.0. Usage: Install django-pagination and save the snippet in templates/pagination/pagination.html then {% paginate %} will work fine. See [Django-paginaation on Bootstrap CSS](http://ronbeltran.blogspot.com/2012/05/django-pagination-bootstrap-css.html)

  • django-pagination
  • bootsrap-css
Read More

HttpResponseSendfile

An HttpResponse for giving the user a file download, taking advantage of X-Sendfile if it's available, using FileWrapper if not. Usage: HttpResponseSendfile('/path/to/file.ext') To bypass the fallback: HttpResponseSendfile('/path/to/file.ext', fallback=False) This has been tested working with Lighttpd 1.4.28's mod_fastcgi.

  • download
  • sendfile
  • x-sendfile
Read More

Django mediagenerator folder bundler

This code will put an entire folder into your media bundle - instead of having to write out every file in a given folder: *It assumes your static root is a absolute directory* **Usage** MEDIA_BUNDLES = ( ('init.js', 'coffeescript/init.coffee', ), bundle_builder('libraries.js', 'javascript/vendor'), bundle_builder('main.js', 'coffeescript', exclude=['init.js',]), bundle_builder('templates.js', 'eco'), ) **Notes** You may wish to use [cache_utils](http://pypi.python.org/pypi/django-cache-utils) or similar to avoid crawling the filesystem every time the site loads

  • django
  • wildcard
  • django-mediagenerator
  • mediagenerator
Read More

2955 snippets posted so far.