Snippet List
It's often useful to dynamically create filter criteria, and Q objects are useful for that, but sometimes you need to make a combined Q composed of various alternates. This bit of code eases the awkwardness of creating the first Q so that there's a combiner, plus the odd case of no criteria.
CIDR ( http://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing ) is a well-known IP range syntax. This CIDR_LIST class can be used to make ranges of IPs considered "internal" for Django's debugging and security purposes. (Django only ever needs to do "ip in INTERNAL_IPS" so __contains__ is sufficient for the purpose.)
For example, to make localhost and the entire block of 10.0.0.* considered to be internal, use:
INTERNAL_IPS = CIDR_LIST([
'127.0.0.1',
'10.0.0.0/24'
])
- debugging
- security
- ip
- cidr
- internal_ips
Sometimes you have an uncontrolled amount of text in a horizontally constrained space.
The wrappable filter places zero-width breaking spaces into the given text so that it can wrap at any point, as necessary for the containing width. Sometimes better than eliding (chopping long text...) or cropping/scrolling overflow.
- template
- filter
- typography
Based loosely on [Eric's middleware](http://ericholscher.com/blog/2009/sep/5/debugging-django-production-revisited/), this middleware will show the technical 500 page (which you'd get if DEBUG == True) to any user who is (1) superuser and (2) a member of the settings.TECHNICAL_500_GROUP_NAME group. (If no setting exists, 'Technical Errors' is the presumed group name.
I agreed with the comments that caching should be unnecessary given the (presumptive) edge case of exception + superuser. Assuming you don't have tons of superusers, this code is a good bit simpler.
- admin
- user
- auth
- debugging
- 500
When executing custom sql, the temptation is to use fetchall or fetchone, since the API for fetchmany is a bit awkward. (fetchall makes all records resident in client memory at once; fetchone takes a network round-trip to the DB for each record.)
This snippet, hoisted from django.db.models.sql.query.results_iter, presents a nice, simple iterator over multiple fetchmany calls which hits a sweet spot of minimizing memory and network usage.
This blog post outlined how to get the user from the session key:
http://scottbarnham.com/blog/2008/12/04/get-user-from-session-key-in-django/
Unfortunately, it assumes DB-backed session and auth backends. This isn't required, so this snippet provides a backend-agnostic way to do the same thing.
>>> skey = 'ea0ed02d35d43aeaf20b3ef516f51396'
>>> user_from_session_key(skey)
<User: jeremyd>
jdunck has posted 8 snippets.