Login

All snippets written in Python

Snippet List

Django Dictionary Model

This is a model that implements (most of) the python dictionary interface. Meaning, you can work with this model exactly like a python dictionary, and it handles querying the database for it's values, saving/deleting the helper objects, etc. I wrote this originally when I needed to store an arbitrary dictionary in the database, and decided to work it up into a near-complete implementation of a dictionary. In order to make sure that the dictionary is the most optimized possible, I have a static method that can be used for retrieval. Feel free to ignore it if you don't care about optimizing database queries. Here's an example: Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49) [GCC 4.2.1 (Apple Inc. build 5646)] on darwin Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from binder.models import Dictionary >>> d = Dictionary.getDict('Foobar') >>> print d {u'Foobar': u'omgbbq', u'HAHAHAH': u"who's afraid of a big, black, bat?"} >>> d['pot'] = 'The kettle is black.' >>> print d {u'Foobar': u'omgbbq', u'pot': u'The kettle is black.', u'HAHAHAH': u"who's afraid of a big, black, bat?"} >>> print d['pot'] The kettle is black. >>> for k, v in d.iteritems(): ... print k +":", v ... Foobar: omgbbq HAHAHAH: who's afraid of a big, black, bat? pot: The kettle is black. >>> print d.keys() [u'Foobar', u'HAHAHAH', u'pot'] >>> print d.values() [u'omgbbq', u"who's afraid of a big, black, bat?", u'The kettle is black.'] >>> There's several more functions that I've implemented; check the code to see. (An interesting note: DictField saves immediately upon making a change, which is good to keep in mind in case that functionality isn't expected.) Hope someone finds this useful. :) --Chris

  • model
  • python
  • dict
  • dictionary
Read More

Updated version of StripWhitespaceMiddleware (v1.1)

Tightens up response content by removed superflous line breaks and whitespace. By Doug Van Horn ---- CHANGES ---- v1.1 - 31st May 2011 Cal Leeming [Simplicity Media Ltd] Modified regex to strip leading/trailing white space from every line, not just those with blank \n. ---- TODO ---- * Ensure whitespace isn't stripped from within <pre> or <code> or <textarea> tags.

  • middleware
  • strip
  • whitespace
Read More

A Django form field that accepts an uploaded image and creates a resized image attached with a push-pin

PushPinImageField is a Django form field that is a sub-class of an ImageField. The field accepts an image to upload and based on certain settings, notably the size of the resulting image, the sizes and colors of 3 different borders, as well as the color of the push pin, a re-sized image is created with a colorized push pin in the top-center. A live demo of the field as well as more detailed usage instructions are available as a [blog entry](http://www.robmisio.com/blog/2/).

  • django
  • image
  • thumbnail
  • form
  • field
  • custom-field
Read More

Sorl thumbs for the lazy

Sorl thumbs for the lazy. **Usage:** {% thumb p.image "noimage.png" %} *tags.py* goes into your templatetags directory. *includes/thumb.html* goes into your templates directory. [Fork it here.](https://gist.github.com/985439)

  • sorl-thumbnail
Read More

Using reverse with success_url in class based generic views

If you did tried to use `reverse` function to set `success_url` in class based generic views and you have got an exception, this helper function may help. Put this snipped in some file, for example utils.py and import this function.

  • reverse
  • class-based-generic-view
  • success_url
Read More

HTML5 filter for XXS

Usefull for TinyMCE, to allow some HTML but be vunarable by XXS attacks You need to install html5lib sudo easy_install html5lib

  • template
  • filter
  • security
  • sanitize
  • xss
Read More

Model Locking Mixin & Decorator (MySQL Advisory Locks)

This code provides a mixin and decorator which, when used together, can provide advisory locking on model methods. It provides locking by using MySQL's advisory lock system. See the example at the bottom of the code. This is a convenient and easy way to guarantee your model methods have exclusive access to a model instance. The LockableObjects class requires a MySQL backend, but it could be modified to use other back-end locking systems. The lock name generation in `LockableObject.get_lock_name()` could be altered to create much more complex locking schemes. Locking per-object, per-method for example.. Lock attempts have a timeout value of 45 seconds by default. If a timeout occurs, EnvironmentError is raised. **See the bottom of the script for an example** > **Instructions:** * **1:** Place the code in locking.py somewhere in your path * **2:** In your models.py (or any script with an object you want to lock): `from locking import LockableObject, require_object_lock` * **3:** In the model you want locking for, add the `LockableObject` mixin * **4:** Decorate the method you want to be exclusively locked with `@require_object_lock`

  • model
  • mysql
  • decorator
  • mixin
  • locking
Read More
Author: pio
  • 0
  • 2

models ColorField with clean minimal widget

A simple model ColorField that allows picking from a predefined list (currently picked up from settings.py The widget displays as a row of coloured SPAN's with the hex code inside. Simply click to choose a color. (requires jQuery in the page assigned to it's normal $ shortcut. Easy to change this is you don't use jQuery in this way)

  • models
  • admin
  • jquery
  • widget
  • custom-field
  • modelfield
Read More

When saving in admin it will call model save() twice.

When I save this in admin, it will call model save() twice Django version 1.2.3, using settings 'admin.development' Development server is running at http://127.0.0.1:8080/ Quit the server with CONTROL-C. [18/May/2011 10:08:22] "GET /admin/onixcodes/bookbatch/ HTTP/1.1" 200 38211 [18/May/2011 10:08:22] "GET /admin/jsi18n/ HTTP/1.1" 200 4256 [18/May/2011 10:08:29] "GET /admin/onixcodes/bookbatch/55/ HTTP/1.1" 200 9811 [18/May/2011 10:08:29] "GET /admin/jsi18n/ HTTP/1.1" 200 4256 save!! save!! [18/May/2011 10:08:33] "POST /admin/onixcodes/bookbatch/55/ HTTP/1.1" 302 0 [18/May/2011 10:08:33] "GET /admin/onixcodes/bookbatch/ HTTP/1.1" 200 38364 [18/May/2011 10:08:33] "GET /admin/jsi18n/ HTTP/1.1" 200 4256 Anyone has any suggestion? Thanks.

  • admin
  • save()
  • twice
Read More

Serve from STATIC_ROOT

Assuming you have defined STATIC_ROOT correctly in settings.py, and have installed staticfiles_urlpatterns() in urls.py (as demoed in the code, taken from Django's staticfiles docs), the code from static_root_finder.py can be used to simply serve static files in development from STATIC_ROOT directly, avoiding complicated setups in case we just want to have a bunch of static files in one directory.

  • staticfiles
  • STATIC_ROOT
Read More

Decorator and context manager to override settings

Overriding settings ------------------- For testing purposes it's often useful to change a setting temporarily and revert to the original value after running the testing code. The following code doubles as a context manager and decorator. It's used like this: from django.test import TestCase from whatever import override_settings class LoginTestCase(TestCase): @override_settings(LOGIN_URL='/other/login/') def test_login(self): response = self.client.get('/sekrit/') self.assertRedirects(response, '/other/login/?next=/sekrit/') The decorator can also be applied to test case classes: from django.test import TestCase from whatever import override_settings class LoginTestCase(TestCase): def test_login(self): response = self.client.get('/sekrit/') self.assertRedirects(response, '/other/login/?next=/sekrit/') LoginTestCase = override_settings(LOGIN_URL='/other/login/')(LoginTestCase) On Python 2.6 and higher you can also use the well known decorator syntax to decorate the class: from django.test import TestCase from whatever import override_settings @override_settings(LOGIN_URL='/other/login/') class LoginTestCase(TestCase): def test_login(self): response = self.client.get('/sekrit/') self.assertRedirects(response, '/other/login/?next=/sekrit/') Alternatively it can be used as a context manager: from django.test import TestCase from whatever import override_settings class LoginTestCase(TestCase): def test_login(self): with override_settings(LOGIN_URL='/other/login/'): response = self.client.get('/sekrit/') self.assertRedirects(response, '/other/login/?next=/sekrit/')

  • settings
  • decorator
  • contextmanager
Read More

2955 snippets posted so far.