Login

All snippets written in Python

Snippet List

blocksetter

Sometimes you need to set a little bit more complex variable in the template (e.g. Title), that is being used more than once. this simple tag defines "blockset" tag. {% blockset variable-name %}{%endblockset} everything inside body (between blockset/endblockset) is being assigned to the variable "variable-name". I have found this quite useful with translations, or setting the title, where you out several variables into one sentence. Drop me an email if you will find this useful.

  • templatetag
  • block
  • set
Read More

Cache Manager

I had a problem: too many fetches from the DB. So, how to reduce load on the database without major changes to the code? Cache Manager is the answer. I've managed to reduce number of DB hits as much as 80% in some cases (dictionaries, complex relations). It is using standard cache mechanisms. I'm using it with mathopd. This is a very simple solution, instead of standard Manager, put this in your model definition as: `objects = CacheManager()` Then everythere elase in the code instead of all() or get(...) call all_cached() or get_cached(). I've kept original methods intact, to have an dual access, when you really, really must have frest data from the DB, and you can't wait for cache to expire. This is much easier to work with, then manually getting fetched data from the cache.No change to your existing code 9except model) and voila! Additionally if you have some data, you would like to store with your serialized object (e.g. related data, dynamic dictionaries), you can do this in the model method '_init_instance_cache'). Drop me an email if you find this useful. :)

  • cache
  • model
  • manager
Read More

Authenticate against Active Directory

I put this in a file called auth.py, then referenced it in the settings.py like so: AUTHENTICATION_BACKENDS = ('myproject.myapp.auth.ActiveDirectoryBackend',) This has been tested on my office network, with the following setup: Django 0.96 Python 2.4.4 python-ldap Fedora Core 5 (On the server hosting Django) AD Native Mode 2 Windows 2003 AD servers

  • auth
  • ldap
  • active-directory
  • backend
Read More

User post_save signal to auto create 'admin' profile

**How to use:** 1. puts this code at the end of the `models.py` file who haves the User Profile class declared; 2. verify if your User Profile class has the name 'UserProfile'. If not, change the code to the right name. **About:** this snippet makes the ORM create a profile each time an user is created (or updated, if the user profile lost), including 'admin' user.

  • admin
  • user
  • userprofile
Read More

lazy url reverse()

Since the decorators of your views are evaluated during parsing urls.py you have an 'chicken - egg' problem. The method reverse() can't be used since urls.py is not read. This snippets evaluates reverse() lazy. [Related ticket: 5925](http://code.djangoproject.com/ticket/5925) Django 1.4 (current trunk) has a lazy reverse.

  • decorator
  • reverse
  • lazy
Read More

function_tag

register any python function as a tag with an optional name. usage: in templatetags: @function_tag() def foo(arg): return do_something(arg) in template: {% foo arg %} or {% foo arg as variable %}{{ variable.bar }}

  • tag
  • function
Read More

SeparatedValuesField

A Django newforms field which takes another newforms field during initialization and validates every item in a comma-separated list with this field class. Please use it like this: from django.newforms import EmailField emails = CommaSeparatedValuesField(EmailField) You would be able to enter a string like "[email protected],[email protected]" because every email address would be validated when clean() is executed. This of course also applies to any other Field class. You can define the sepator (default: ",") during initialization with the `separator` parameter like this: from django.newforms import EmailField` emails = SeparatedValuesField(EmailField, separator="###")

  • newforms
  • field
  • comma
  • separated
Read More

Integer list to pattern function

This function can be util for transform pattern lists like these to strings: >>> list_to_pattern([42, 43, 44, 45]) '42-45' >>> list_to_pattern([15, 49, 50, 51, 52]) '15,49-52' >>> list_to_pattern([0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]) '0-13' You can use also the pattern to list function at [http://www.djangosnippets.org/snippets/495/](http://www.djangosnippets.org/snippets/495/)

  • list
  • integer
Read More

Pattern to integer list function

This function can be util for transform pattern strings like these to list: >>> pattern_to_list('42-45') [42, 43, 44, 45] >>> pattern_to_list('15,49-52') [15, 49, 50, 51, 52] >>> pattern_to_list('0-13') [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] You can use also the list to pattern function at [http://www.djangosnippets.org/snippets/496/](http://www.djangosnippets.org/snippets/496/)

  • list
  • integer
Read More

CountryField

**How to use** put this code somewhere you want, import CountryField and use

  • field
  • country
  • countries
Read More

Cache decorator

You can use this cache all your functions' output, except dynamic things like connection.cursor.

  • django
  • cache
  • decorator
Read More
Author: xyb
  • 0
  • 9

nginx x-accel-redirect protection of static files

This snippet requires nginx as your front end server (for serving static files) and any django enabled server as a backend that only gets the dynamic requests (I use apache with mod_python). If you have no idea what I'm talking about, you probably won't need this snippet. I previously tried something [similar](http://www.djangosnippets.org/snippets/62/) just using mod_python, but this was too unstable for my needs (the PythonAuthenHandler seems to be called multiple times for no apparent reason). The patch from that snippet was also used as a base for [this ticket](http://code.djangoproject.com/ticket/3583). This is part of an authentication mechanism I use for protecting static files. Nginx has the so called x-accel-redirect feature, that tells nginx to serve an internal (read 'protected') file if the backend response has the ['X-Accel-Redirect'] header set. No other headers are touched, but by deleting all relevant headers in the default django response, nginx will create those headers for us. The usage is pretty simple: * set up nginx as a proxy for apache + mod_python + django (google for this if you don't know how) * configure nginx as shown in the code snippet (for testing leave out the internal part to see if the files are accessible) * configure your urls.py to point to the validation view * make your sites hrefs point to the view instead of the file directly (those real urls will be completely hidden from your visitors) * Done!

  • authentication
  • nginx
Read More

AutoSlugField

This is a simple solution aimed at saving some time when you simply want to get a slug from a model field just before saving.

  • fields
  • slug
  • field
Read More

Renderer decorator

You can use this as a decorator for your views, this way you can return a simple dictionary and the decorator will do the rest. **@TODO:** Automatically set the template based on the app/view request

  • shortcut
  • render
Read More

2956 snippets posted so far.