Login

Display arbitrary models

Author:
bjornkri
Posted:
July 17, 2008
Language:
Python
Version:
.96
Score:
0 (after 0 ratings)

Template tag for displaying a list of arbitrary models. Useful for life-stream kind of pages that display blog entries, links, photos etc ordered by date. Example

Usage: something like:

{% for object in object_list %}
    {% display_excerpt object %}
{% endfor %}

Will look for app/model_excerpt.html by default, and fall back on a generic display_excerpt.html, or returns the object's string representation as a last fallback.

display_excerpt.html might look something like:

<a href="{{ object.get_absolute_url }}">{{ object }}</a>

Any model you throw at it should have a get_absolute_url and a string representation of some sort, so this gives you the bare minimum of a title and a link to a detail page.

display_excerpt takes an optional argument to set the template suffix. This might be handy for generating different formatting for feeds, for instance:

{% for object in object_list %}
    {% display_excerpt object "feed" %}
{% endfor %}

This will look for app/model_feed.html to render the object.

Got lots of help from mattmcc on #django for this one, thanks!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
from django import template

def display_excerpt(object, template_suffix='excerpt'):
    excerpt = object._meta.app_label + "/" + object._meta.module_name + "_" + template_suffix + ".html"
    try:
        t = template.loader.select_template([excerpt, 'display_excerpt.html'])
    except template.TemplateDoesNotExist:
        return str(object)
    c = template.Context({"object": object})
    return t.render(c)

register = template.Library()
register.simple_tag(display_excerpt)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 1 week ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 9 months, 4 weeks ago
  5. Help text hyperlinks by sa2812 10 months, 3 weeks ago

Comments

Please login first before commenting.