Sometimes you want to create a temporal variable to store something or do anything you want with it, problem is that django template system doesn't provide this kind of feature. This template tag is just for that.
Syntax::
{% assign [name] [value] %}
This will create a context variable named [name] with a value of [value]
[name] can be any identifier and [value] can be anything. If [value] is a callable, it will be called first and the returning result will be assigned to [name]. [value] can even be filtered.
Example::
{% assign count 0 %}
{% assign str "an string" %}
{% assign number 10 %}
{% assign list entry.get_related %}
{% assign other_str "another"|capfirst %}
{% ifequal count 0 %}
...
{% endifequal %}
{% ifequal str "an string" %}
...
{% endifequal %}
{% if list %}
{% for item in list %}
...
{% endfor %}
{% endif %}
Put this code somewhere in one of your INSTALLED_APPS `__init__.py` file. This code will replace the django.template.loader.get_template with cached version. Standard get_template function from django reads and parses the template code every time it's called. This version calls (if DEBUG set to False) it only once per template. After that it gets a Template object from template_cache dictionary. On django http server with template code like that:
{% extends "index.html" %}
{% block content %}
{% if form.has_errors %}
<p>Your username and password didn't match. Please try again.</p>
{% endif %}
<form method="post" action=".">
<table>
<tr><td><label for="id_username">Username:</label></td><td>{{ form.username }}</td></tr>
<tr><td><label for="id_password">Password:</label></td><td>{{ form.password }}</td></tr>
</table>
<input type="submit" value="login" />
<input type="hidden" name="next" value="{{ next }}" />
</form>
{% endblock %}
ab -n 100 on mac os x 10.5 core 2 duo 2 ghz with 2 GB of RAM gives
forge-macbook:~ forge$ ab -n 100 http://127.0.0.1:8000/login/
This is ApacheBench, Version 2.0.40-dev <$Revision: 1.146 $> apache-2.0
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Copyright 2006 The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient).....done
Server Software: WSGIServer/0.1
Server Hostname: 127.0.0.1
Server Port: 8000
Document Path: /login/
Document Length: 934 bytes
Concurrency Level: 1
Time taken for tests: 0.432934 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 120200 bytes
HTML transferred: 93400 bytes
Requests per second: 230.98 [#/sec] (mean)
Time per request: 4.329 [ms] (mean)
Time per request: 4.329 [ms] (mean, across all concurrent requests)
Transfer rate: 270.25 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.0 0 0
Processing: 3 3 1.5 4 12
Waiting: 3 3 1.2 3 12
Total: 3 3 1.5 4 12
Percentage of the requests served within a certain time (ms)
50% 4
66% 4
75% 4
80% 4
90% 4
95% 5
98% 10
99% 12
100% 12 (longest request)
without template caching, and
forge-macbook:~ forge$ ab -n 100 http://127.0.0.1:8000/login/
This is ApacheBench, Version 2.0.40-dev <$Revision: 1.146 $> apache-2.0
Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/
Copyright 2006 The Apache Software Foundation, http://www.apache.org/
Benchmarking 127.0.0.1 (be patient).....done
Server Software: WSGIServer/0.1
Server Hostname: 127.0.0.1
Server Port: 8000
Document Path: /login/
Document Length: 934 bytes
Concurrency Level: 1
Time taken for tests: 0.369860 seconds
Complete requests: 100
Failed requests: 0
Write errors: 0
Total transferred: 120200 bytes
HTML transferred: 93400 bytes
Requests per second: 270.37 [#/sec] (mean)
Time per request: 3.699 [ms] (mean)
Time per request: 3.699 [ms] (mean, across all concurrent requests)
Transfer rate: 316.34 [Kbytes/sec] received
Connection Times (ms)
min mean[+/-sd] median max
Connect: 0 0 0.0 0 0
Processing: 3 3 0.9 3 9
Waiting: 2 3 0.9 3 8
Total: 3 3 0.9 3 9
Percentage of the requests served within a certain time (ms)
50% 3
66% 3
75% 3
80% 3
90% 3
95% 5
98% 8
99% 9
100% 9 (longest request)
with caching enabled.
In both cases DEBUG is set to False.
This is a little base class that I use to display forms in a readonly mode. Providing a simple javascript on the front end to allow a user to click an **edit** link that will show/hide the actual form.
To use it simply inherit from it. Then in your templates do the following:
`{{ form.as_readonly_table }}`
**Other Notes**
* **form.html**
`{% for field in bound_fields %}
{% include "newforms/field.html" %}
{% endfor %}`
* **field.html**
`{% if field.errors %}
<tr>
<td> </td>
<td>{{ field.errors }}</td>
</tr>
{% endif %}
<tr>
<th style="text-align:right">
<label for="id_{{ field.name }}">{{ field.label }}{% if field.field.required %}<span class="required"><sup>*</sup></span>{% endif %}</label>
</th>
<td>{{ field }}
{% if field.help_text %}
<p class="helptext">({{ field.help_text }})</p>
{% endif %}
</td>
</tr>`
**Explanation:**
I think this shortcut can be util for who uses JSON many times and does not want to write same code everytime.
**Setup:**
Saves the snippet as `myproject/utils.py` or add the code to some place in your project with same ends.
**Use in a view:**
from myproject.utils import render_to_json
from django.contrib.admin.models import User
def json_view(request):
admin_user = User.objects.get(username='admin')
return render_to_json(
'json/example.json',
locals(),
)
**Update:**
This code can be used as complement to [http://www.djangosnippets.org/snippets/154/](JsonResponse snippet) too.
Extended extends tag that supports passing parameters, which will be made
available in the context of the extended template (and all the way up the
hierarchy).
It wraps around the orginal extends tag, to avoid code duplication, and to
not miss out on possible future django enhancements.
Note: The current implementation will override variables passed from your
view, too, so be careful.
Some of the argument parsing code is based on:
http://www.djangosnippets.org/snippets/11/
Examples:
{% xextends "some.html" %}
{% xextends "some.html" with title="title1" %}
{% xextends "some.html" with title="title2"|capfirst %}
Usage:
{% if item|IN:list %}
The item is in the list.
{% endif %}
{% if customer.age|LE:18 %}
Go play out here.
{% endif %}
{% if product.price|add:delivery_cost|GT:balance %}
Insufficient funds.
{% endif %}
You've got the idea.
Special thanks to [guychi](http://www.djangosnippets.org/snippets/379/).
I tried to use [Joshua's](http://www.djangosnippets.org/users/joshua/) nice and very useful [getattr template filter (#38)](http://www.djangosnippets.org/snippets/38/), but ran into a few problems.
I used it on objects outside of my control (admin internals, coughcough) and on some of them the code didn't catch the resulting exceptions. So I improved the error handling a bit.
Furthermore, the code now also returns the *value of a callable* instead of the callable *itself* (last 4 lines).
Looking at my code though, it can certainly be improved further.
I wanted to have the possibility to use a wiki-like markup style in my flatpages for various purposes (embedding images, quoting, etc.)
After a few dead ends I came up with this, which is quite nice I think.
> It basically takes a named tag, loads the corresponding template, passes in all arguments, renders the template and replaces the named tag with the result.
*The markup looks like this:*
> [[example:value to pass|option1=somevalue option2=values can have spaces too! without having to put them in quotes option3=some other value]]
*This results in:*
* Filter tries to load wiki/wiki_example.html
* If it is loaded, it passes an WikiElement containing the value and the options to the template, renders it and replaces the tag with the rendered template
*In the "wiki/wiki_example.html" template you can use it like this:*
{{param.value}}
{{param.opts.option1}}
Or loop over param.opts.iteritems.
Usage:
{% ifmodulo forloop.counter 4 0 %}
<!-- do something -->
{% else %}
<!-- do something else -->
{% endifmodulo %}
or
{% ifnotmodulo 5 3 %}
<!-- do something -->
{% else %}
<!-- do something else -->
{% endifmodulo %}
When the third parameter does not exist, it is assumed you're checking for values different than 0.
Sorts a list of HTML anchor tags based on the anchor's contents. This is useful, for example, when combining a static list of links with a dynamic list that needs to be sorted alphabetically. It ignores all attributes of the HTML anchor.
{% load anchorsort %}
{% anchorsort %}
<a href="afoo.jpg">Trip to Fiji</a>
<a href="bfoo.jpg">Doe, a deer, a female deer!</a>
{% for link in links %}
<a class="extra" href="{{ link.href|escape }}">{{ link.name|escape }}</a>
{% endfor %}
{% endanchorsort %}
Note that case (capital vs. lower) is ignored. Any HTMl within the node itself **will not be removed**, so sorting `<a>Bar</a><a><strong>Foo</strong><a/>` will sort as `<a><strong>Foo</strong></a><a>Bar</a>` because `<` is logically less than `b`.
Tag library that provides support for *macros* in Django templates.
**Usage example:**
**0)** Save this file as
<yourapp>/templatetags/macros.py
**1)** In your template load the library:
{% load macros %}
**2)** Define a new macro called 'my_macro' with parameter 'arg1':
{% macro my_macro arg1 %}
Parameter: {{ arg1 }}
{% endmacro %}`
**3a)** Use the macro with a String parameter:
{% usemacro my_macro "String parameter" %}
**3b)** or with a variable parameter (provided the context defines 'somearg' variable, e.g. with value "Variable parameter"):
{% usemacro my_macro somearg %}
**3c)** **!!NEW!!** `usemacro` now also supports filters attached to parameters:
{% usemacro my_macro "lowercase parameter"|upper %}
Output of the above code would be:
Parameter: String parameter
Parameter: Variable parameter
Parameter: LOWERCASE PARAMETER
**4)** **!!NEW!!** Alternatively save your macros in a separate file, e.g. "mymacros.html" and load it into the current template with:
{% loadmacros "mymacros.html" %}
Macros can take *zero or more arguments* and both context variables and macro arguments are resolved in macro body when used in `{% usemacro ... %}` tag.
Bear in mind that Macros are local to each template file and are not inherited through `{% extends ... %}` blocks.
One of the things about Django that has always irked me is that there seems to be no standard facility for just loading a page and displaying it, simply. Yes, there is the flatpages module, but it is primarily designed for loading content from a DB. While you specify a custom template and put in junk values for the DB content, it just feels like extra, unnecessary work.
Thinking about the problem some more, I borrowed from the idea of flatpages and implemented a view that will load an otherwise unmapped template off the filesystem and render it. This is very useful when converting an existing site over. Just copy your files over. No need to map anything in the URL conf or use the admin to add any flatpage entries. Since it'll render the template, too, you can even use tags and what not, so it need not be a static page.