**Usage** (*in template*):
<img src="{{ MEDIA_URL }}2007/images/{% filter split:","|random %}theimage1.jpg,something2.jpg,thirdisthecharm.jpg{% endfilter %}" />
I decided to make it simple, because one template creator wanted to add random images to different places of templates. Creating something huge, like external image filename parsing was not necessary in this case.
This is tag similar to *timesince* and *timeuntil*, which work great until you starting giving timesince dates in the future or timeuntil dates in the past. Timedelta tag will humanize output correctly for both future and past dates using *now* as a default reference date (or a specified reference date as argument)
now = Apr 27 2007
futuredate = May 5 2007
pastdate = Jan 5 2007
{{ futuredate|timedelta }} will output "in 1 week, 1 day"
{{ pastdate|timedelta }} will output "3 months, 2 weeks ago"
**Now redundant any anything >0.96**, as `form_for_*` methods now have a `fields` attribute
`formfield_callback`s are a bit difficult to use, here's a helper method to create a callback function to use with the `form_for_instance` and `form_for_model` methods.
Example usage:
person_callback = new_callback(exclude=['password', 'can_add_staff', 'is_staff'])
def form_for_person(person):
return form_for_instance(person, formfield_callback=person_callback)
This will return a template-friendly list of dictionaries when using custom SQL. The dictionary can be accessed just as a normal model/queryset.
Example of use (in view):
qkeys = ['artist','album']
query = """
SELECT "artist","album" FROM "music"
"""
new_list = csql(request,query,qkeys)
(in template)
{% for row in new_list %}
{{ row.artist }} {{ row.album }}
{% endfor %}
This is to be used as a template filter. See [django documentation](http://www.djangoproject.com/documentation/templates_python/#writing-custom-template-filters) for adding custom filters.
Example of use:
name = "bart simpson"
`{{ name|cap }}` will convert 'name' to "Bart Simpson"
It works on space-separated names, as well as the following:
* converts "mcfly" to "McFly";
* converts "o'neill" to "O'Neill";
* converts "barker-bradley" to "Barker-Bradley"
Originally posted by [akaihola](http://www.djangosnippets.org/users/akaihola/) as [snippet #169](http://www.djangosnippets.org/snippets/169/). I just redid it as a filter.
This is some very simple middleware that keeps track of the last 3 succesful requests for each visitor. This can be useful if you want to redirect the visitor to a previous path without relying on a hidden field in a form, or if you simply want to check if a visitor has recently visited a certain path.
Note that this relies on the session framework and visitors actually accepting cookies.
This can be easily modified to hold more requests if you have a need for it.
Simple template filter to encode a variable to JSON format
Usage:
{% load json_filters %}
{% block content %}
<script type="text/javascript"><![CDATA[
var items = {{ items|jsonify }};
]]></script>
{% endblock %}
I'm using JsonResponse for the views but I also want to have preloaded JSON data into the page output
Renders an select field with some optgroups. Some options can be outside the optgroup(s).
The options and labels should be in a tuple with ((label, choices),) where choices is a tuple ((key, value), (key2, value2)). If a label is null or blank, the options will not belong to an opt group.
Useful for when you want to use an instance's values as the initial values of a form which you didn't use `form_for_instance` to create.
Handles foreign keys and many-to-many fields just fine.
A slightly improved version of [snippet #195](/snippets/195/) which keeps the logic but makes use of the `simple_tag` decorator to drastically simplify the code.
For an alternative to this sort of tag, check out the media context processor in my [template_utils app](http://code.google.com/p/django-template-utils/).
Sometimes it's nice to know if your visitors came from a search engine such as Google or Yahoo. I use this as a component in determining the popularity of blog articles for search keywords, so I know which articles to automatically feature or suggest. Maybe you'd like to use it to highlight the visitor's search terms on the page.
This isn't actually middleware in the sense that it defines any of the middleware interfaces. It's intended to be the base for a middleware method that you write, depending on what you want to happen when you detect that the visitor came from a search engine. In the example `process_view` method, I detect when the request is going to use the `object_detail` view and log the search query for that object in the database.
This a small but very handy view that gives you a convenient direct access to your templates.
Now suppose you saved the snippet under `misc.py`, it's critical to add this snippet (or a similar one, once you get the idea) to your `urls.py`:
if settings.DEBUG:
# Direct Templates
urlpatterns += patterns('misc',
(r'^template/(?P<path>.*)$', 'direct_to_template', {'template': '%(path)s'}),
)
Now you are able to access any of your templates, in different directories by specifying their path after `template/`. e.g., http://example.com/template/news/index.html
Of course you can change it as you want, you can also add other values to the dict argument, the only required key is `'template'`. The whole dict is made available in the template as a context.
All GET parameters are made available in the template too. So `http://example.com/template/news/index.html?title=Testing Title` will make the `{{ title }}` var available in your template. So you can substitute basic variables quickly.
This is was inspired by [django.views.generic.simple.direct_to_template](http://www.djangoproject.com/documentation/generic_views/#django-views-generic-simple-direct-to-template)