Quick and dirty "what I'm reading" plugin

Nov 22, 2008 Django

(Note: that partner id in the absolute_url below is mine. I won't object if you want to use it, but you might be better off signing up for your own: Powells.com Partner Program)

The model:

class Book(models.Model):
    RATING_CHOICES = (
        ('1', '1'),
        ('2', '2'),
        ('3', '3'),
        ('4', '4'),
        ('5', '5'),
    )

    STATUS_CHOICES = (
        ('1', 'have read'),
        ('2', 'currently reading'),
        ('3', 'want to read'),
    )

    title = models.CharField(max_length=255)
    author_first_name = models.CharField(max_length=255)
    author_last_name = models.CharField(max_length=255)
    isbn = models.CharField(max_length=255)
    status = models.IntegerField(max_length=2, blank=True, null=True, choices=STATUS_CHOICES)
    rating = models.IntegerField(max_length=2, blank=True, null=True, choices=RATING_CHOICES)
    active = models.BooleanField(default=True)
    created_at = models.DateTimeField(auto_now_add=True)

    def __unicode__(self):
        return u"%s" % self.title

    def get_absolute_url(self):
        return "http://www.powells.com/partner/33557/biblio/%s/" % self.isbn

    class Meta:
        ordering = ['status']



The admin:

from django.contrib import admin

from myblogproject.plugins.books.models import Book

class BookAdmin(admin.ModelAdmin):
    list_display = ('title', 'author_last_name', 'author_first_name', 'status', 'rating',)
    list_filter = ('status', 'rating',)



The inclusion tag:

from django import template
from django.core.exceptions import ObjectDoesNotExist

from myblogproject.plugins.books.models import Book
register = template.Library()

def book_list():
    current_books = Book.objects.filter(status=2).order_by('-created_at')[:1]
    tbr_books = Book.objects.filter(status=3).order_by('-created_at')[:5]
    return {'current_books': current_books, 'tbr_books': tbr_books}
register.inclusion_tag('book_list.html')(book_list)



The template used to render the tag:

<div id="sidebar-list">

{% if current_books %}
    What I'm reading:
    <ul>
    {% for book in current_books %}
        <li><a href="{{ book.get_absolute_url }}" target="new">{{ book.title }}</a><br />
    {% endfor %}
    </ul>
{% endif %}

{% if tbr_books %}
    On the pile:
    <ul>
    {% for book in tbr_books %}
        <li><a href="{{ book.get_absolute_url }}" target="new">{{ book.title }}</a><br />
    {% endfor %}
    </ul>
{% endif %}

</div>



Plugging the tag into my sidebar template:

    {% load plugin_tags %}
    {% library_list %}



My favorite line from the custom template tags documentation:

    "Tags are more complex than filters, because tags can do anything."
Wash my car? Make me a sandwich?