Login

All snippets

Snippet List

TableSelectMultiple Widget

A widget for selecting from a list of `Model` instances using `MultipleChoiceField` which renders a table row for each choice, consisting of a column for a checkbox followed by a column for each item specified in `item_attrs`, which must specify attributes of the objects passed as choices.

  • forms
  • table
  • widget
  • selectmultiple
Read More

Authenticate against a Windows domain controller

To activate, store this file as `mysite/winauth.py` and use in settings.conf: AUTHENTICATION_BACKENDS = ('mysite.winauth.DomainControllerAuthBackend',) Needs [pywin32 extensions](http://sourceforge.net/projects/pywin32/) installed (and obviously only runs on Windows).

  • authentication
  • domain
  • windows
  • controller
  • pdc
Read More

Create nice looking PDFs from developer documentation

You need htmldoc, rst2html, the Python Imaging Libraray, BeautfiulSoup and spoon. The Debian/Ubuntu-packages are called htmldoc, python-docutils, python-imaging and python-beautifulsoup You can get spoon.py http://beautifulspoon.googlecode.com/svn/trunk/spoon.py To create the pdf files you have to call the script from django_src/docs Here is an example output: http://henning.cco-ev.de/django/essential.pdf

  • pdf
  • documentation
  • docs
Read More

Movable Type Import

This is a quick and dirty way to import blog entries and comments from Movable Type. Sorry I don't have time to document it better. Hopefully it will help you get started if you're looking to move from MT to Django.

  • type
  • import
  • movable-type
  • movable
  • mt
Read More

Little middleware that create a facebook user

**How to use**: 1. Install [**PyFacebook** package](http://wiki.developers.facebook.com/index.php/PythonPyFacebookTutorial). 2. After make all steps in tutorial above, put this code in your app's models.py module (you maybe prefer split it and put the middleware class in some other file). 3. Put the FacebookUserMiddleware python-path in the MIDDLEWARE_CLASSES in your settings.py (after facebook.djangofb.FacebookMiddleware). You probably will add some fields to FacebookUser model class :)

  • middleware
  • user
  • facebook
Read More

Pickled Object Field

*Incredibly useful for storing just about anything in the database (provided it is Pickle-able, of course) when there isn't a 'proper' field for the job:* A field which can store any pickleable object in the database. It is database-agnostic, and should work with any database backend you can throw at it. Pass in any object and it will be automagically converted behind the scenes, and you never have to manually pickle or unpickle anything. Also works fine when querying. **Please note that this is supposed to be two files, one fields.py and one tests.py (if you don't care about the unit tests, just use fields.py)**

  • model
  • db
  • orm
  • database
  • pickle
  • object
  • field
  • pickled
Read More

Automate unique slugs

If you want unique values for a slug field, but don't want to bother the user with error messages, this function can be put into a model's save function to automate unique slugs. It works by appending an integer counter to duplicate slugs. The item's slug field is first prepopulated by slugify-ing the source field. If that value already exists, a counter is appended to the slug, and the counter incremented upward until the value is unique. For instance, if you save an object titled Daily Roundup, and the slug daily-roundup is already taken, this function will try daily-roundup-2, daily-roundup-3, daily-roundup-4, etc, until a unique value is found. Call from within a model's custom save() method like so: `unique_slug(item, slug_source='field1', slug_field='field2')` where the value of field slug_source will be used to prepopulate the value of slug_field. Comments appreciated!

  • slug
  • save
Read More

Link filter

Almost too dumb to be worth posting but its saved me a lot of typing. Instead of: <div> <a href="{{ object.get_absolute_url }} class="object-icon">{{ object }}</a> </div> just put: <div>{{ object|link }}</div>

  • filter
  • links
Read More

URL redirects middleware

Sometimes you need to make redirects that involve domains, you can't define those on the site urls, this middleware lets you define multiple redirects on your site settings. Note: *You also can use the web server to do this, but I have found this middleware a useful tool to quickly or temporarily define redirects*. Depending on your needs you may also find useful [snippet 434](http://www.djangosnippets.org/snippets/434/).

  • middleware
  • url
  • redirect
  • domain
Read More

OwnerField

This is a little helper for associating an owner to a newly created object, in this case making the assumption that the current user is always the owner. It removes the necessity of adding a custom save hook to your model. get_current_user comes from this middleware trick to cache the current user: http://code.djangoproject.com/wiki/CookBookThreadlocalsAndUser

  • model
  • user
  • field
  • owner
  • ownerfield
Read More

BirthYearField

A form field to prompt for a year of birth with suitable sanity checks. Usage eg: yob = BirthYearField(label="What year were you born?")

  • form
  • field
  • year
  • birth
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

Mathematical Captcha

Simple mathematical captcha where human is asked to solve a simple mathematical calculation like 2+3=?. Don't require database access or external libraries like PIL. To use MathCaptchaForm subclass it and add your fields. For example of usage and discussion about security of this captcha comparing with traditional image captcha please see my blog entry [Improved Mathematical Captcha](http://www.mysoftparade.com/blog/improved-mathematical-captcha/)

  • captcha
Read More

prevent GET or POST requests

This will return HTTP 405 if request was not POSTed. same way you can forbide POST request, change 'POST' to 'GET' Decorators provided for your convenience.

  • view
  • request
  • post
Read More

NewForms Readonly / Edit Pattern

This is a little base class that I use to display forms in a readonly mode. Providing a simple javascript on the front end to allow a user to click an **edit** link that will show/hide the actual form. To use it simply inherit from it. Then in your templates do the following: `{{ form.as_readonly_table }}` **Other Notes** * **form.html** `{% for field in bound_fields %} {% include "newforms/field.html" %} {% endfor %}` * **field.html** `{% if field.errors %} <tr> <td>&nbsp;</td> <td>{{ field.errors }}</td> </tr> {% endif %} <tr> <th style="text-align:right"> <label for="id_{{ field.name }}">{{ field.label }}{% if field.field.required %}<span class="required"><sup>*</sup></span>{% endif %}</label> </th> <td>{{ field }} {% if field.help_text %} <p class="helptext">({{ field.help_text }})</p> {% endif %} </td> </tr>`

  • template
  • newforms
  • readonly
  • edit-mode
Read More

3110 snippets posted so far.