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"
Block tag version of [escapejs](http://www.djangoproject.com/documentation/templates/#escapejs). Handy when using inclusion tags to generate AJAX responses.
[A comment on a recent blog entry of mine](http://www.b-list.org/weblog/2008/feb/25/managers/#c63422) asked about a setup where one model has foreign keys pointing at it from several others, and how to write a manager which could attach to any of those models and query seamlessly on the relation regardless of what it's named.
This is a simple example of how to do it: in this case, both `Movie` and `Restaurant` have foreign keys to `Review`, albeit under different names. However, they both use `ReviewedObjectManager` to provide a method for querying objects whose review assigned a certain rating; this works because an instance of `ReviewedObjectManager` "knows" what model it's attached to, and can introspect that model, using [Django's model-introspection API](http://www.b-list.org/weblog/2007/nov/04/working-models/), to find out the correct name to use for the relation, and then use that to perform the query.
Using model introspection in this fashion is something of an advanced topic, but is extremely useful for writing flexible, reusable code.
**Also**, note that the introspection cannot be done in the manager's `__init__()` method -- at that point, `self.model` is still `None` (it won't be filled in with the correct model until a bit later) -- so it's necessary to come up with some way to defer the introspection. In this case, I'm doing it in a method that's called when the relation name is first needed, and which caches the result in an attribute.
The class LocationField renders a form field with map (from google maps) and a mark. It allows the user to drag the mark to point at some particular location, whose value (lat, lng) is saved in a hidden field.
It requires jquery and google maps.
cache_smart template tag is a drop in replacement for default cache tag by Django but with the added bonus to be more resistant against dog-pile/stampeding effect.
This snippet uses a extra cache entry to store a stale time so we don't have to pickle/unpickle to store this extra value.
If this cache entry returns None, as in expired it will reset the stale timeout 30 seconds in the future so further calls will just return the old value while this request is regenerating the new value.
**warning**
Don't use both cache template tags!
Sometimes we want to render items as cells in table with fixed row-count and computable col-count shape and vice versa. It's not difficult to do it with compute odd and even row, col index, but more common way is to use some reshape function. Theare are simple TAG for it: "table", with use reshape function and FILTER "flatindex" wich can use to get flat index in nested loops (may use with table like in this example).
Example of usage:
`{# List filials must exists in context! #}
{% load table %}
<table border="0" width="100%">
{% table filials "3x?" %}
{% for row in table_obj %}
<tr>
{% for record in row %}
{% if record %}
<td class="mf_table_cell" onclick="selcell('filial_{{forloop|flatindex}}')">
<img src="/art/filial.gif" style="margin-bottom: 4px;"/><br/>
<span id="filial_{{forloop|flatindex}}" class="mf_table_unselcell">{{ record }}</span>
</td>
{% else %}
<td class="mf_table_cell">
</td>
{% endif %}
{% endfor %}
</tr>
{% endfor %}
{% endtable %}
</table>`
/best regards
Yosifov Pavel
Many models are tightly coupled to the default Django `User` model (`django.contrib.auth.models.User`).
Sometimes this user model just doesn't fit everyone's needs. By using `UserForeignKey` it is possible to make the `User` model configurable, encouraging loose coupling.
Additionally, this can help to prevent circular imports between `User` and another model.
Use it like a standard `ForeignKey`... it accepts all the same arguments.
If you want to use a `User` model other than the default, just add `USER_MODEL` to your settings file.... it uses dotted notation (`app_label.model_name`).
Example:
class BlogPost(models.Model):
user = UserForeignKey(related_name="blog_posts")
title = models.CharField(...)
content = models.TextField(...)
I had a need to colorize the nicks for the new DjangoBot Logger. Instead of managing a collection of names and corresponding colors we decided it would be more simple to just "hash" the nickname using a colorize filter. This causes the same nickname to always appear in the same color.
It's a template tag used to create boxes with nested divs (useful to keep the templates DRY). For example:
{% menubox titlevar %}
Content here
{% endmenubox %}
will generate the html with the nested divs
div class=box
div class=box-outer
div class=box-inner
Headline
Content
/div
/div
/div
[more detail on this blog post](http://pedro.valelima.com/blog/2007/sep/26/boxes-template-tags/)
I love the Django templates and ORM, but I prefer to use CherryPy as my web server. So I want to be able to do the equivalent of "python manage.py sql" but without actually needing to have a Django application. So I stick all of my models in a file named "models.py" and then run this script and it prints out all of the CREATE TABLE statements for my database.