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
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.
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/).
The django admin (as of 1.3) doesn't allow for short_description (and other ModelAdmin function attributes) to be a callable. Until that happens, this handy snippet allows you to return dynamic descriptions.
Note, I haven't actually tested this yet -- but I plan to when I have the free time.
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)
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.
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`
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)
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.
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.
Add this to your apache config:
`<Directory /path/to/media>
WSGIAccessScript /path/to/access.wsgi
</Directory>`
Save the snippet as access.wsgi. Set up the paths, and do some authorization checking.
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/')