Login

All snippets written in Python

Snippet List

Sign a string using SHA1, then shrink it using url-safe base65

Sometimes it's useful to sign data to ensure the user does not tamper with it - for example, cookies or hidden form variables. SHA1 is cryptographically secure but weighs in at 40 characters, which is pretty long if you're going to be passing the data around in a URL or a cookie. These functions knock an SHA1 hash down to just 27 characters, thanks to a base65 encoding that only uses URL-safe characters (defined as characters which are unmodified by Python's urllib.urlencode function). This compressed hash can then be passed around in cookies or URLs, and uncompressed again when the signature needs to be checked. UPDATE: You probably shouldn't use this; see [http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/](http://fi.am/entry/urlsafe-base64-encodingdecoding-in-two-lines/) for a smarter approach based on Python's built-in base64 module.

  • security
  • base65
  • signing
  • cookies
  • hashlib
  • hashes
  • sha1
Read More

simple guestbook

a simple guestbook. the guestbook-area and entries can (and should) be styled by CSS. The template extends a "base.html", which should contain a "content" block. The Model is very simple without moderation, admin-comment or any other advanced features, but its easy to extend. i.e. add a Field "active=models.BooleanField()" and add "exclude=['active']" to the forms.EntryForm.Meta class for moderated Entries. Now you can switch the entries on/off in the admin-interface by setting active=True/False this snippet is public domain, use for everything you want. UPDATE: added basic SPAM protection (a do_not_fill field), but you might want to try a captcha-form/Field like snippet 812

  • guestbook
  • guest
  • book
Read More

Notifications Middleware for Session-Backed Messages

simple middleware and context processor for session-based messaging with types Heavily inspired by patches on ticket 4604. Differs in that in this a notification has type. Installation: * add notifications.NotificationMiddleware to MIDDLEWARE_CLASSES * and notifications.notifications to TEMPLATE_CONTEXT_PROCESSORS That assumes notifications.py is on pythonpath. If notifications.py lives in your project dir, prefix those with '(projectname).' Example use: * request.notifications.create('Some bland information message.') * request.notifications.create('Some more exciting error message.', 'error') Example template code: `{% if notifications %} <ul id="notifications"> {% for notification in notifications %}<li class="{{ notification.type }}">{{ notification.content }}</li> {% endfor %} </ul> {% endif %}` [rendered example](http://traviscline.com/blog/2008/08/23/django-middleware-session-backed-messaging/)

  • middleware
  • flash
  • notifications
Read More

Login with email or username

A simple backend which allows you to login with either an email address or a username. It should be combined with another backend for checking permissions: AUTHENTICATION_BACKENDS = ( 'myproject.accounts.backends.EmailOrUsernameModelBackend', 'django.contrib.auth.backends.ModelBackend' )

  • email
  • login
  • auth
  • backend
Read More

SQL Function Decorator

This decorator will replace a method on a model with a class method that executes SQL in the functions doc string.

  • sql
  • model
  • decorator
Read More

Upload, Progressbar with sessions

This script is an adaptation from http://www.djangosnippets.org/snippets/678/ . Here, it doesnt use the cache middleware but relies on sessions. The script set a session cookie to identify the upload and track it to make it available for a progress bar like this one : http://www.djangosnippets.org/snippets/679/ . Note the progress bar cannot work with development server as it is single-threaded. Tested with apache/mod_python and mod_wsgi. any comments appreciated ;)

  • upload
  • handler
  • sessions
  • progressbar
Read More

models with order (+admin editing)

Use this abstract model if you want to add "order" to a given model. Once you do, you will get automatic "up" and "down" links for each model row. One problem is that if the user sorts by another row, the up and down links are still there, but now don't make a lot of sense.

  • models
  • admin
  • order
Read More

Autogenerate admin classes in admin.py

Tired of adding admin classes to admin.py whenever you add a model? This admin.py automatically keeps itself up-to-date with your models.py file. It assumes if you have a model: MyModel, you want an admin class called AdminMyModel. Regards, Luke Miller

  • django
  • models
  • admin
Read More

Django and jQuery -- pulling info from a long-running process

Another sample of how to integrate Django and jQuery. === This starts a function in views.py that takes a long time to finish. It sets a session variable so that another function can report on the situation. We use jquery and ajax to 'pull' that data from Django so as to provide a progress report. I don't yet know how to background a long-running process, but this is an okay stop-gap method to use. I hope. \d

  • ajax
  • json
  • jquery
  • data
  • progress
  • pull
Read More

Ajax form with jQuery

I recently got a form working via jQuery and Django. This was not easy for me to do and I thought I'd record my finding here. The form submits via jQuery and the "form" plugin. Please visit jQuery's home page to find all those links. This code handles: * urls.py -- passing both normal and 'Ajax' urls to a view. * views.py -- Handling both kinds of requests so that both normal and ajax submits will work. * The HTML template with the script for submitting and some bling. Error handling === I like to stay DRY so the idea of checking the form for errors in javascript *and* checking it in Django irks me. I decided to leave that up to Django, so the form submits and gets validated on the server. The error messages are sent back to the browser and then displayed.

  • ajax
  • urls
  • fields
  • views
  • jquery
  • form
  • errors
Read More

Cacheable resources

This snippet provides a template tag that automatically replaces references to any resource you want cached forever with a version of the file that is based on the MD5 sum. For an image, you would use something like: {% load utils %} <img src="{% cacheable "/media/images/logo.png" %}"/> To install it, put a setting in your settings.py file called "DOCUMENT_ROOT", put the python code into a templatetag-friendly file (e.g. app/templatetags/utils.py), load that template tag, then use either a string literal, as above, or a variable name to refer to your resource: <img src="{% cacheable my_media_file %}"/> The cacheable resource will be used when `DEBUG = False`, but in DEBUG mode, the path you give it will be passed back untouched (so you don't have a proliferation of cacheable files as you develop). Django will need write access to the directory you've specified as "DOCUMENT_ROOT" (so it can copy the original file into a forever-cacheable version). You'll also need to set up your webserver to serve files called "MYMD5SUMNAME.cache.(js|css|png|gif|jpg) with an expires header that is far into the future. The goal here is to create a version of your file that will never have to be downloaded again. If you ever change the original file, the MD5 sum will change and the changed file's cacheable name will reflect that. Besides simply changing the name of resources, if the file is a JavaScript or CSS file, and you've specified `MINIFY = True`, the file will be minified using YUI compressor.

  • md5
  • cacheable
  • cacheing
Read More

2955 snippets posted so far.