Use this code in *change_form.html* in your projects admin templates to add a character counter beside the input field(s) in admin to let users know how many characters they have remaining for a particular input field. The total number of characters allowed is determined by the max_length in your model for the models.CharField you're using this with.
This code is designed to add the counter after the input field, but could easily be customized to fit the style of any admin. If the number of characters remaining is 10 or less the background color changes to yellow to visually warn the user.
**Usage Examples:**
In this example only the input field with id=id_pull_quote will receive the counter:
$(document).ready(function() {
$("#id_pull_quote").counter();
});
You could also apply the counter to all input fields on a page:
$(document).ready(function() {
$("form input[@maxlength]").counter();
});
**Note:** *You have to download jQuery to your project and place the appropriate call in order for this to work. The best place to do this is in the extrahead block. I left my call in as an example but your path and file name will probably vary.*
Credit for base jQuery code goes to Brad Landis at [bradlis7.com](http://www.bradlis7.com).
Couldn't get the original to work, and wanted more functionality (scale on x or y coordinates)
<img src="{{ object.image.url }}" alt="original image">
<img src="{{ object.image|thumbnail:"250w" }}" alt="image resized to 250w x (calculated/scaled)h ">
<img src="{{ object.image|thumbnail:"250h" }}" alt="image resized to (calculated/scaled)w x 250h h ">
<img src="{{ object.image|thumbnail:"250x200" }}" alt="image resized to 250wx200h ">
<img src="{{ object.image|thumbnail }}" alt="image resized to default 200w (or whatever you default it to) format">
Original http://www.djangosnippets.org/snippets/192/
Adapted http://www.djangosnippets.org/snippets/955/
Sampled From:
http://batiste.dosimple.ch/blog/2007-05-13-1/
http://vaig.be/2008/05/17/stdimagefield-improved-image-field-for-django/
All you need to do is include the file you save this as in your other templates. The css and javascript is right in the file. Fully customizable. Very easy.
Click a date to choose a single date. Click a second date to choose a range. A third click will act as a first click.
note: you also will want to customize the django template specific variables in elements with ids:
s_date
e_date
cal_month
if you change those, it's not even really django specific, but i use this in my form for time off requests at work.
A simple template filter that detects [iPernity](http://www.ipernity.com) static URLs and creates clickable thumbnail for them. Use it with [Lightbox](http://www.huddletogether.com/projects/lightbox2/) or any other funky image overlay script.
Your HTML code may contain this:
<p>A short example <img
src="http://...ipernity..."
title="The Description" />.</p>
After applying this filter it will become:
<p>A short example <a
href="http://...large version..."
title="The Title"><img
alt="The Title"
src="http://...thumb version..."/>
</a>.</p>
Thats all! You may have a look at this: [iPernity and static URLs](http://www.ipernity.com/group/api-users/discuss/20098)
Works exactly like the standard "extends" tag but enables one to fallback on a default template. This tag is LIMITED, as it falls back to the next template with the same name that DOES NOT contain "extends_default" (does NOT simulate full inheritance, just a single level).
A partial solution to problems like http://jeffcroft.com/blog/2008/aug/05/default-templates-django/.
MIT licensed.
Django's templates don't provide much in the way of arithmetic: there is an "add" filter and that is about it. Even if sub, mult and div filters are implemented, it is difficult to chain filters while preserving some complicated expression, such as ((x+3)4-(2-y)/12.75). However, this expression can be converted into Reverse Polish Notation: x 3 + 4 * 2 y - 12.75 / - which is just a sequence of operations (push-value or apply-operator) and can be chained.
To use these filters, first create a new stack for the expression with name|stnew (pass it some locally unique value). To push a number (or template variable) onto the stack, call name|stpush:number (note that you have to tell stpush the name of the stack to push onto). To pop, call name|stpop. To perform an operation, call name|st[add,sub,mult,div,mod]:number. All numbers are integers if they look like integers, or floats otherwise (integers are turned into floats upon division if they need to be). All of these functions return the name of the stack so that they can be chained. When the calculation is finished (i.e. the answer is at the bottom of the stack) call name|stget to retrieve it.
Example (this was used to calculate an inline CSS value:
`left: {{ forloop.counter|stnew|stpush:res.stwkday|stpush:"9.35"|stmult|stpush:res.get_item_left|stpush:"2.75"|stadd|stadd|stget }}em;`
This module defines a template tag `{% ifactive %}` that lets you determine which page is currently active. A common use case is for highlighting the current page in a navigation menu.
It uses the same syntax for specifying views as the `{% url %}` tag, and determines whether a particular page is active by checking if the same view is called with the same arguments, instead of just comparing URLs. As a result, it can handle cases where different URLs map to the same view.
Example usage:
<a {% ifactive request page1 %}class='active'{% endifactive %}
href='{% url page1 %}'>Page 1</a>
<a {% ifactive request page2 %}class='active'{% endifactive %}
href='{% url page2 %}'>Page 2</a>
...
<a {% ifactive request pageN %}class='active'{% endifactive %}
href='{% url pageN %}'>Page N</a>
It also can be extended to further reduce the amount of repetitive code. For instance, you could write a template tag that has class='active' as the block contents, and always gets the variable from context['request']:
def do_activeif(parser, token):
"e.g. <a {% activeif page1 %} href='{% url page1 %}'>Page 1</a>"
tag_args = token.contents.split(' ')
view_name = tag_args[1]
args, kwargs = _parse_url_args(parser, tag_args[2:])
return ActiveNode('request', view_name, args, kwargs, NodeList(TextNode('class="active"')))
register.tag('activeif', do_activeif)
Note that you will have to add the ActiveViewMiddleware to your settings.py:
MIDDLEWARE_CLASSES = (
...,
'path.to.this.module.ActiveViewMiddleware'
)
You may also want to add this template tag as a built-in, so you don't have
to call `{% load %}`. In somewhere that's imported by default (e.g. where you
define your views), add:
from django import template
template.add_to_builtins('path.to.this.module')
Jinja2 is an alternative template system that can be plugged into django.
It offers greator flexibility in presentation logic; if you find the django template system too restrictive, you should have a look at Jinja2
(The syntax is very similar).
In Jinja, you don't need costum tags (most of the time), because you can call functions and pass them parameters too!
The only problem is that you cannot "load" functions from the template, this "loading" must be done by the code that renders the template. Same goes for filters and tests.
If you need only two or three functions/filters, no problem, you can manually add them to the Environment object; but this method doesn't really scale with real-life webapps.
This module/snippet offers a solution by allowing the user to define application-specific functions and filters and load them into the jinja2 environment automatically.
Here's how to use this:
1. Install Jinja2 (for a quick & dirty installation, you can just put the jinja2 folder in a folder that's in PYTHONPATH)
2. Save this python module somewhere and call it something meaningful (I have it as jinja.py in my project directory)
3. Whenever you need to respond (an HttpResponse) with a template that's rendered by jinja, import this module and call `return jrespond( template_name, context )`
4. Any filters or functions you define in any of your applications will be readily available inside the template (see the documentation in code)
A simple filter which divides an iterable (list, tupe, string, etc) in chunks, which can then be iterated over separately. A sample of the filter usage is given: a gallery template in which I needed to display images in a table, three images per row, one row for images followed by one row for their descriptions.
Add this code to you your context_processors.py in your project and then install it in your settings.py TEMPLATE_CONTEXT_PROCESSORS. In your template you can print out a segment of a url by using {{ segment_1 }}. For example if you're on the page "/mysite/section1/section2/" and you used {{ segment_2 }} it would print section1.
This idea was taken from Expression Engines URL Segments, http://expressionengine.com/docs/templates/globals/url_segments.html.
This comes in handy if you only want to do something in your template if the page your on has a particular segment.
FYI, I haven't used this in a production setting yet so it could be buggy still.
This is a mod I made to the Django simple_tag system to let the simple_tags access comments. I plan to try and get it integrated into the trunk, so it's mainly here so (a) the people on django-developers can see it, and (b) while I'm waiting, or if it doesn't get put in the trunk, people can use it.
**Installing**
1. Open the module `django.template.__init__`, wherever that lives.
2. Scroll down to the beginning of " `class Library:` "
3. Find the simple_tag function (" `def simple_tag(self,func):` ")
4. Replace the function (even the whitespace before each line) with the code snippet.
**Usage**
1. When defining a simple tag (see the [docs](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#shortcut-for-simple-tags) for more info), have the first parameter in your function be named "`context`". Otherwise, an error will be thrown. It can accept other parameters like normal.
2. Use `register.simple_tag(my_function_name, takes_context=True)` to register your function as one that will use the context.
3. The tag's function can access the context like a dictionary - to get a value, just use `context['cheese']`, or to set one, use `context['cheese'] = 'Limberger'`. Due to the context's mutability, this will affect the context in the main template as well.
**Notes**
This code hasn't been tested in a "production environment", but I did test my modifications thoroughly, and if you don't add `takes_context=True`, `simple_tag` will behave exactly as normal. Of course, if there is a problem, make sure you leave a comment.
**Code**
Since most of the code is hacked up from other Django library functions, and to prepare for if and when it's merged into the trunk, it's released under the BSD license.
Works much like an inclusion_tag but allows the template_name to be given as an argument or defaults to partials/MODELNAME.html where MODELNAME is 'got' from the context object you want to render. Its very rough so improvements very welcome!
It would be nice to be able to pass new context variables as template tag [keyword] arguments for use in the template to be rendered so you basically have a template tag equivalent for render_to_string...
Example usage in a template:
{% render_partial post %} or {% render_partial post partials/super_post.html %}