Login

Most bookmarked snippets

Snippet List

Choice Field and Select Widget With Optional Optgroups

Renders an select field with some optgroups. Some options can be outside the optgroup(s). The options and labels should be in a tuple with ((label, choices),) where choices is a tuple ((key, value), (key2, value2)). If a label is null or blank, the options will not belong to an opt group.

  • newforms
  • widgets
  • select
  • optgroup
  • option
Read More

MintCache

MintCache is a caching engine for django that allows you to get by with stale data while you freshen your breath, so to speak. The purpose of this caching scheme is to avoid the dog-pile effect. Dog-piling is what normally happens when your data for the cache takes more time to generate than your server is answering requests per second. In other words if your data takes 5 seconds to generate and you are serving 10 requests per second, then when the data expires the normal cache schemes will spawn 50 attempts a regenerating the data before the first request completes. The increased load from the 49 redundant processes may further increase the time it takes to generate the data. If this happens then you are well on your way into a death spiral MintCache works to prevent this scenario by using memcached to to keep track of not just an expiration date, but also a stale date The first client to request data past the stale date is asked to refresh the data, while subsequent requests are given the stale but not-yet-expired data as if it were fresh, with the undertanding that it will get refreshed in a 'reasonable' amount of time by that initia request I don't think django has a mechanism for registering alternative cache engines, or if it does I jumped past it somehow. Here's an excerpt from my cache.py where I'v just added it alongside the existing code. You'll have to hook it in yourself for the time being. ;-) More discussion [here](http://www.hackermojo.com/mt-static/archives/2007/03/django-mint-cache.html).

  • cache
  • mint
  • memcached
Read More

caching parsed templates

Put this code somewhere in one of your INSTALLED_APPS `__init__.py` file. This code will replace the django.template.loader.get_template with cached version. Standard get_template function from django reads and parses the template code every time it's called. This version calls (if DEBUG set to False) it only once per template. After that it gets a Template object from template_cache dictionary. On django http server with template code like that: {% extends "index.html" %} {% block content %} {% if form.has_errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} <form method="post" action="."> <table> <tr><td><label for="id_username">Username:</label></td><td>{{ form.username }}</td></tr> <tr><td><label for="id_password">Password:</label></td><td>{{ form.password }}</td></tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {% endblock %} ab -n 100 on mac os x 10.5 core 2 duo 2 ghz with 2 GB of RAM gives forge-macbook:~ forge$ ab -n 100 http://127.0.0.1:8000/login/ This is ApacheBench, Version 2.0.40-dev <$Revision: 1.146 $> apache-2.0 Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Copyright 2006 The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: WSGIServer/0.1 Server Hostname: 127.0.0.1 Server Port: 8000 Document Path: /login/ Document Length: 934 bytes Concurrency Level: 1 Time taken for tests: 0.432934 seconds Complete requests: 100 Failed requests: 0 Write errors: 0 Total transferred: 120200 bytes HTML transferred: 93400 bytes Requests per second: 230.98 [#/sec] (mean) Time per request: 4.329 [ms] (mean) Time per request: 4.329 [ms] (mean, across all concurrent requests) Transfer rate: 270.25 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.0 0 0 Processing: 3 3 1.5 4 12 Waiting: 3 3 1.2 3 12 Total: 3 3 1.5 4 12 Percentage of the requests served within a certain time (ms) 50% 4 66% 4 75% 4 80% 4 90% 4 95% 5 98% 10 99% 12 100% 12 (longest request) without template caching, and forge-macbook:~ forge$ ab -n 100 http://127.0.0.1:8000/login/ This is ApacheBench, Version 2.0.40-dev <$Revision: 1.146 $> apache-2.0 Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Copyright 2006 The Apache Software Foundation, http://www.apache.org/ Benchmarking 127.0.0.1 (be patient).....done Server Software: WSGIServer/0.1 Server Hostname: 127.0.0.1 Server Port: 8000 Document Path: /login/ Document Length: 934 bytes Concurrency Level: 1 Time taken for tests: 0.369860 seconds Complete requests: 100 Failed requests: 0 Write errors: 0 Total transferred: 120200 bytes HTML transferred: 93400 bytes Requests per second: 270.37 [#/sec] (mean) Time per request: 3.699 [ms] (mean) Time per request: 3.699 [ms] (mean, across all concurrent requests) Transfer rate: 316.34 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 0.0 0 0 Processing: 3 3 0.9 3 9 Waiting: 2 3 0.9 3 8 Total: 3 3 0.9 3 9 Percentage of the requests served within a certain time (ms) 50% 3 66% 3 75% 3 80% 3 90% 3 95% 5 98% 8 99% 9 100% 9 (longest request) with caching enabled. In both cases DEBUG is set to False.

  • template
  • cache
  • performance
  • optimization
Read More

Include captchas from recaptcha.net

Recaptcha is a free service that helps you protect your forms against spam bots by displaying a picture showing 2 words or playing an audio file telling 8 digits for the visually handicapped. After registration on http://recaptcha.net a private and a public key are generated. Put the keys in settings.py. Find client code for recaptcha at http://pypi.python.org/pypi/recaptcha-client. Put the file captcha.py into application root.

  • captcha
  • recaptcha
Read More
Author: b23
  • 8
  • 29

AdminPeepingMiddleware

Peeping middleware, that replaces active user to another one for current http request. Admin permissions required to activate, so you can place this snippet even on the production server. Very useful for debugging purposes. Wish it to be part of Django. How to use: Put this middleware after all other middlewares in the list. Then just add ?as_user=username or &as_user=username to the url, where username is the name of user whose views you want to see.

  • middleware
  • admin
  • view
  • permissions
  • peep
Read More

PyIf Template Tag (Conditional Tag)

Cheers to limodou for getting me thinking about this. The only problem with his implementation is that it doesn't support Django's "." syntax for accessing array/dict elements. In the Django style of allowing simple syntax for designers while allowing for greater flexibility, and less template duplication for conditionals that were previously impossible to represent in templates, I modified Django's built-in If tag. This is an adaptation/enhancement to Django's built in IfNode {% if ... %} that combines if ifequal ifnotequal into one and then adds even more. This Supports 1. ==, != 2. not .... 3. v in (1,"y",z) 4. <=, <, >=, > 5. nesting (True and (False or (True or False))) How to use it: {% pyif i == 1 or (5 >= i and i != 7) and user.first_name in ('John', 'Jacob') %} 'Tis true. {% else %} 'Tis false. {% endif %} I hope you like it.

  • template
  • tag
  • templatetag
  • if
  • conditional
  • ifequal
  • ifnotequal
Read More

Alphabetic filter for admin

This snippet is based on [#748](http://www.djangosnippets.org/snippets/748/). Adds filtering by first char (alphabetic style) of values in the admin filter sidebar. The example below results in this filter: By name that starts with All A B G M X urls.py example (only for register the filter): import <your project>.admin.filterspecs models.py example: from django.db import models class Person(models.Model): name = models.CharField(max_length=40) name.alphabetic_filter = True admin.py example: class Admin: list_filter = ['name']

  • filter
  • admin
  • filterspec
Read More

Digg-like paginator, updated

This is an updated version of http://www.djangosnippets.org/snippets/628/ now working with Django's new Paginator class, instead of the deprecated ObjectPaginator. See: http://blog.elsdoerfer.name/2008/05/26/diggpaginator-update/

  • pagination
  • paginator
  • digg
Read More

Newforms Autocomplete Widget with Scriptaculous

From [here](http://gacha.id.lv/blog/26/01/2007/django-autocompletefield/) with litle improvements. [More about Script.aculo.us and Django](http://wiki.script.aculo.us/scriptaculous/show/IntegrationWithDjango)

  • ajax
  • newforms
  • autocomplete
Read More

Django JQuery Autocomplete for Model Selection

This is a general JQuery Autocomplete Form Field for selecting any model instance in your forms. 1 Download jquery.1.2.6 and the jquery autocomplete plugin http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/, place theme somewhere in your media directory (in this case {{ MEDIA__URL}}/js/ 2 copy fields.py to anywhere in your python-path (in this case utils.fields) 3 create a view for the ajax request that receives a query and returns a key|value list, and register it in your urls.py 4 Just Use the fields in any form like in forms.py

  • selection
  • model
  • jquery
  • autocomplete
Read More

Decorator to limit request rates to individual views

Example: @limit("global", 3, 10, per_ip=True) def view(request, ...): The example limits the view to one request every 3 seconds per ip address. The limit is shared by every view that uses the string "global" (first parameter), which is an arbitrary string. Request succeed until the accumulated requested time in seconds (second parameter) exceeds the limit (third parameter).

  • request
  • rate
  • limit
Read More

Command to dump data as a python script

This creates a fixture in the form of a python script. Handles: 1. `ForeignKey` and `ManyToManyField`s (using python variables, not IDs) 2. Self-referencing `ForeignKey` (and M2M) fields 3. Sub-classed models 4. `ContentType` fields 5. Recursive references 6. `AutoField`s are excluded 7. Parent models are only included when no other child model links to it There are a few benefits to this: 1. edit script to create 1,000s of generated entries using `for` loops, python modules etc. 2. little drama with model evolution: foreign keys handled naturally without IDs, new and removed columns are ignored The [runscript command by poelzi](http://code.djangoproject.com/ticket/6243), complements this command very nicely! e.g. $ ./manage.py dumpscript appname > scripts/testdata.py $ ./manage.py reset appname $ ./manage.py runscript testdata

  • dump
  • manage.py
  • serialization
  • fixtures
  • migration
  • data
  • schema-evolution
  • management
  • commands
  • command
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

Ajax progress bar

This snippet is an example of an ajax progress bar (using jquery) that you might use in conjunction with <http://www.djangosnippets.org/snippets/678/>. 1. Generates a uuid and adds X-Progress-ID to the forms action url. 2. Adds the progress bar to the page. (you'll have to add some css styling for this) 3. Makes period ajax requests to update the progress bar.

  • ajax
  • javascript
  • upload
  • file
  • progress
Read More

3109 snippets posted so far.