Add the attribute "rel='lightbox'" to all Links, if the target is an image.
`<a href="/path/to/image.jpg">Image</a>`
becomes
`<a rel="lightbox" href="/path/to/image.jpg">Image</a>`
Works for JPG, GIF and PNG Files.
*Incredibly useful for storing just about anything in the database (provided it is Pickle-able, of course) when there isn't a 'proper' field for the job:*
A field which can store any pickleable object in the database. It is database-agnostic, and should work with any database backend you can throw at it.
Pass in any object and it will be automagically converted behind the scenes, and you never have to manually pickle or unpickle anything. Also works fine when querying.
**Please note that this is supposed to be two files, one fields.py and one tests.py (if you don't care about the unit tests, just use fields.py)**
Sometimes you need to make redirects that involve domains, you can't define those on the site urls, this middleware lets you define multiple redirects on your site settings.
Note: *You also can use the web server to do this, but I have found this middleware a useful tool to quickly or temporarily define redirects*.
Depending on your needs you may also find useful [snippet 434](http://www.djangosnippets.org/snippets/434/).
A Django newforms field which takes another newforms field during
initialization and validates every item in a comma-separated list with
this field class. Please use it like this:
from django.newforms import EmailField
emails = CommaSeparatedValuesField(EmailField)
You would be able to enter a string like "[email protected],[email protected]"
because every email address would be validated when clean() is executed.
This of course also applies to any other Field class.
You can define the sepator (default: ",") during initialization with the
`separator` parameter like this:
from django.newforms import EmailField`
emails = SeparatedValuesField(EmailField, separator="###")
Watch out! Previous versions of this snippet (without the values list) were vulnerable to SQL injection attacks. The "correct" solution is probably to wait until [ticket 4102](http://code.djangoproject.com/ticket/4102) hits the trunk. But here's my temporary fix while we wait for that happy day.
Django's model.save() method is a PITA:
1. It does a SELECT first to see if the instance is already in the database.
2. It has additional database performance overhead because it writes all fields, not just the ones that have been changed.
3. It overwrites other model fields with data that may be out of date. This is a real problem in concurrent applications, like almost all web apps.
If you just want to update a field or two on a model instance which is already in the database, try this:
update_fields(user,
email='[email protected]',
is_staff=True,
last_login=datetime.now())
Or you can add it to your models (see below) and then do this:
user.update_fields(
email='[email protected]',
is_staff=True,
last_login=datetime.now())
To add it to your model, put it in a module called granular_update, then write this in your models.py:
import granular_update
class User(models.Model):
email = models.EmailField()
is_staff = models.BooleanField()
last_login = models.DateTimeField()
update_fields = granular_update.update_fields
Date-based generic views do not provide pagination by default but Django is very extensible. It provides a Paginator that takes care of pagination. Since date based views usually order by descending order ie from latest entry to the oldest, I used a queryset to order the items (on a field called 'date_pub') and then pass this queryset to the paginator which takes care of the pagination.
Sometimes, when views are particularly complex, it's useful to send the different request methods to different functions. If you have to do this frequently, the repetition gets tiring. This helper class can be used to simplify that.
I've been working on a project where I realized that I wanted to call methods on Python objects *with arguments* from within a Django template.
As a silly example, let's say your application maintains users and "permissions" that have been granted to them. Say that permissions are open-ended, and new ones are getting defined on a regular basis. Your `User` class has a `check_permission(p)` method that return `True` if the user has been granted the permission `p`.
You want to present all the users in a table, with one row per user. You want to each permission to be presented as a column in the table. A checkmark will appear in cells where a user has been granted a particular permission. Normally, in order to achieve this, you'd need to cons up some sort of list-of-dicts structure in Python and pass that as a context argument. Ugh!
Here's how you'd use the `method`, `with`, and `call` filters to invoke the `check_permission` method from within your template. (Assume that you've provided `users` and `permissions` as context variables, with a list of user and permission objects, respectively.)
<table>
<tr>
<th></th>
{% for p in permissions %}
<th>{{ p.name }}</th>
{% endfor %}
</tr>
{% for u in users %}
<tr>
<td>{{ u.name }}</td>
{% for p in permissions %}
<td>
{% if user|method:"check_permission"|with:p|call" %}X{% endif %}
</td>
{% endfor %}
</tr>
{% endfor %}
</table>
The `call_with` method is a shortcut for single-argument invocation; for example, we could have re-written the above as
{% if user|method:"check_permission"|call_with:p %}...{% endif %}
Anyway, this has been useful for me. Hope it's helpful for others!
--chris
P.S., tip o' the cap to Terry Weissman for helping me polish the rough edges!
The django debug screens are great, but only when you can see them. Trying to debug javascript/ajax calls can be kind of a pain. This just a copy/paste of some code in django's internals stuck in a middleware so that exceptions also print to the dev server console.
Allows for a quick startup loading commonly used classes, installed apps, and console utils.
To use: After manage.py shell, enter from somepath.startup import *.
In response to [#366](/snippets/366/), this is a subclass of the `CommentModerator` class from `comment_utils` which does nothing except email the "owner" of an object whenever a new comment is posted on it; all other moderation options remain inactive.
Use this to display a split of page execution time between python and the db in your base template when debugging.
I originally got the base of this code from another snippet, but I can't find it anymore and want to share with new folks because I find this handy.
The XhtmlDegraderMiddleware class is designed to make it easier to deploy XHTML contents onto the World Wide Web. The correct MIME media type for sending XHTML is `application/xhtml+xml` -- the `text/html` media type is also acceptable provided [certain guidelines](http://www.w3.org/TR/2002/REC-xhtml1-20020801/#guidelines) are followed.
The vast majority of web browsers released from 2002 onwards have good XHTML support; this includes Mozilla Firefox, Opera, and Apple Safari. Two notable exceptions are Internet Explorer 7.0 and Netscape Navigator 4.8; instead of displaying XHTML, they present the user with a download dialog instead.
The role of the XHTML Degrader, then, is to automatically detect when browsers do not support XHTML, and to degrade the contents into something they're capable of rendering.
**How it works**
XhtmlDegraderMiddleware checks the content type of all HTTP responses. If the XHTML media type is set, the `Accept` request header is examined to determine whether the user agent actually supports XHTML. If so, the contents is sent unaltered. If not, a number of silent changes are made to make the response more friendly to XHTML-challenged browsers and web crawlers.
Firstly, the `Content-Type` header is set to the HTML media type. Any XML processing instructions are removed, and a `DOCTYPE` is added if none is present. In the case of Internet Explorer, this should ensure the content is rendered in "standards compliance" mode. Empty elements are made to have a space before their trailing slash.
N.B. If an HTTP response is already set to `text/html`, or set to any media type other than `application/xhtml+xml`, the middleware will have no effect. Note also that if you use GZipMiddleware, you should ensure that it appears in your MIDDLEWARE_CLASSES setting before XhtmlDegraderMiddleware, to allow the XHTML Degrader to act first.
This tag makes it easy to include menu or navigation bars in an application's pages, even in a 'tabbed' fashion. (The actual appearance is styled in CSS; this example uses UL tags that are then supposed to be styled by a "display: inline" attribute to be rendered as horizontal bars.)
You're looking at the top-rated snippets currently on the site; if you'd like to contribute, sign up for an account and you'll be able to rate any snippet you see.