If you've ever wanted to dynamically lookup values in the template layer (e.g. `dictionary[bar]`), then you've probably realized/been told to do this in the python layer. The problem is then you often to build a huge 2-D list to hold all of that data.
These are two solutions to this problem: by using generators we can be lazy while still making it easy in the python layer. I'm going to write more documentation later, but here's a quick example:
from lazy_lookup import lazy_lookup_dict
def some_view(request):
users = User.objects.values('id', 'username')
articles = Article.objects.values('user', 'title', 'body')
articles = dict([(x['user'], x) for x in articles])
return render_to_response('some_template.html',
{'data': lazy_lookup_dict(users, key=lambda x: x['id'],
article=articles,
item_name='user')})
Then in the template layer you'd write something like:
{% for user_data in data %}
{{ user_data.user.username }}, {{ user_data.article.title }}
{% endfor %}
This middleware makes the admin error emails a lot more informative: you get the same HTML response that you get with `DEBUG=True`.
It uses the base class defined in [#638](http://www.djangosnippets.org/snippets/638/).
You will probably want to apply the patch for [#6748](http://code.djangoproject.com/ticket/6748) to help avoid slowdowns caused by unintentional database queries. As the ticket (and django-developers thread) notes, it isn't foolproof; you may still find this executing database queries.
Django EmailMessage class has no cc support and has bug in bcc support.
Core developers won't add cc support (see ticket http://code.djangoproject.com/ticket/5790),
and I don't want to wait half a year until they will realize they have a flaw that bcc recipients are sent to regular "to:" recipients and fix it.
So, if you want to use EmailMessage class right now, you'd better use FixedEmailMessage class. Class contract is the same, except for a new cc constructor argument.
**This code will throw deprecation warnings in newer Django checkouts - see the http://www.djangosnippets.org/snippets/773/ for an improved version that should work with the recent trunk.**
objects = MyModel.objects.all()
paginator = DiggPaginator(objects, 10, body=6, padding=2, page=7)
return render_to_response('template.html', {'paginator': paginator}
{% if paginator.has_next %}{# pagelink paginator.next #}{% endif %}
{% for page in paginator.page_range %}
{% if not page %} ...
{% else %}{# pagelink page #}
{% endif %}
{% endfor %}
http://blog.elsdoerfer.name/2008/03/06/yet-another-paginator-digg-style/
A MODPYTHON Apache Log Handler
This module provides a logging Handler class to a MODPYTHON Apache server. Python's standard [logging API](http://www.python.org/doc/2.5/lib/module-logging.html) explains how to [use a handler](http://www.python.org/doc/2.5/lib/multiple-destinations.html).
The handler, by default, writes entries to the Apache error_log using the standard Python logging API.
VIRTUAL HOSTS (Python 2.5)
This handler also supports Apache Virtual Hosts where the mp_server object is available. Then, it writes entries to the specific virtual-host server's error_log.
To get the mp_server object out of Django, you need the **log_extras()** function in your logging call (See the source comments).
This module must be bound to the Python logging API. Use a site_logging.py module to do that as this [related example](http://www.djangosnippets.org/snippets/960/) shows.
This snippet demonstrates the use of the SpecialOps patch ( [link here](http://hackermojo.com/mt-static/archives/2008/02/django-special-ops.html) )to the django 0.96 admin. Once you have the patch, adding actions like these is simple.
You can use the @admin_action decorator on model and manager methods to expose them inside the admin. For manager methods, the method should accept a list of IDs. For model methods, only self should be required.
ModelChoiceField allows you to use filtered queries to simplify your forms. This is great for adding objects but can fall down when you edit an existing object and the original query no longer contains the referenced field (e.g. I like to use an "active" field in several objects).
The fix is simply to include an extra param: Q(pk=object_id). You have to do this in the __init__ method to get the object_id.
A nice thing about this is that it works for ModelForms as well as custom Forms.
Have you ever felt the need to run multiple Django projects on the same memcached server? How about other cache backends? To scope the cache keys, you simply need to prefix. However, since a lot of Django's internals rely on `django.core.cache.cache`, you cannot easily replace it everywhere.
This will automatically upgrade the `django.core.cache.cache` object if `settings.CACHE_PREFIX` is set to a string and the Middleware contains `ScopeCacheMiddleware`.
A thread discussing the merging of this functionality into Django is available on [the dev mailing list](http://groups.google.com/group/django-developers/browse_thread/thread/d45edaafec56da2a).
However, (as of now) nowhere in the thread does anyone mention the reason why this sort of treatment is needed: Many of Django's internal caching helpers use `django.core.cache.cache`, and will then conflict if multiple sites run on the same cache stores.
Example Usage:
>>> from django.conf import settings
>>> from django.core.cache import cache
>>> from scoped_caching import prefix_cache_object
>>> settings.CACHE_PREFIX
'FOO_'
# Do this once a process (e.g. on import or Middleware)
>>> prefix_cache_object(settings.CACHE_PREFIX, cache)
>>> cache.set("pi", 3.14159)
>>> cache.get("pi")
3.14159
>>> cache.get("pi", use_global_namespace=True)
>>> cache.get("FOO_pi", use_global_namespace=True)
3.14159
>>> cache.set("FOO_e", 2.71828, use_global_namespace=True)
>>> cache.get("e")
2.71828
To Install: Simply add `ScopeCacheMiddleware` as a middleware and define `settings.CACHE_PREFIX` and enjoy!
Use this decorator on a function that returns a dict to get a JSON view, with error handling.
Features:
* response always includes a 'result' attribute ('ok' by default)
* catches all errors and mails the admins
* always returns JSON even on errors
This is deprecated. I don't use it anymore, since forms now have the attribute "has_changed".
The method form_changed() returns a boolean value. It is True if the submitted
values of the bound and valid form are different than the initial values.
It works for me. Feedback welcome.
Set debug=True if you want to know what's going on.
Just like `{% spaceless %}`, except a single space is preserved between two inline tags (such as `<a>`, `<em>`, and so on). This lets you use the tag on running text without fear of running two spans of styled text together incorrectly.
This snippet creates thumbnails on-demand from a ImageField with any size using dynamics methods, like ``get_photo_80x80_url`` or ``get_photo_640x480_filename``, etc.
It assumes you have an `ImageField` in your Model called `photo` and have this in your models.py:
import re
from os import path
from PIL import Image
GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$')
`models.py` example:
import re
from os import path
from PIL import Image
from django.db import models
GET_THUMB_PATTERN = re.compile(r'^get_photo_(\d+)x(\d+)_(url|filename)$')
class Photo(models.Model):
photo = models.ImageField(upload_to='photos/%Y/%m/%d')
<snippet here>
Example usage:
>>> photo = Photo(photo="/tmp/test.jpg")
>>> photo.save()
>>> photo.get_photo_80x80_url()
u"http://media.example.net/photos/2008/02/26/test_80x80.jpg"
>>> photo.get_photo_80x80_filename()
u"/srv/media/photos/2008/02/26/test_80x80.jpg"
>>> photo.get_photo_64x64_url()
u"http://media.example.net/photos/2008/02/26/test_64x64.jpg"
>>> photo.get_photo_64x64_filename()
u"/srv/media/photos/2008/02/26/test_64x64.jpg"