Activity Feed with Event Log

Adding an activity feed is simple with the eventlog application. I show you how to get started with it by easily adding it to your project, and how use and administer it.

resources

imagebook/settings.py

INSTALLED_APPS = (
    ...
    'eventlog',
)
image/models.py
from django.db import models
from django.contrib.auth.models import User
from django.template.defaultfilters import slugify

from eventlog.models import log


class Image(models.Model):
    title = models.CharField(max_length=255)
    slug = models.SlugField(blank=True, null=True)
    description = models.TextField(blank=True, null=True)
    rating = models.DecimalField(max_digits=6, decimal_places=5, default=0.0)
    source = models.CharField(max_length=1000)
    user = models.ForeignKey(
        User, blank=True, null=True, on_delete=models.SET_NULL)

    def save(self, args, **kwargs):
        if not self.slug:
            self.slug = slugify(self.title)

        if not self.id:
            log(user=self.user, action='ADD_IMAGE',
                extra={"title": self.title})
        else:
            log(user=self.user, action='UPDATED_IMAGE',
                extra={"title": self.title})

        super(Image, self).save(args, kwargs)

    @models.permalink
    def get_absolute_url(self):
        return ('image_detail', (), {'pk': self.id, 'slug': self.slug})

    def admin_thumbnail(self):
        return "<img src='%s' height='41' width='66' />" % self.source
    admin_thumbnail.allow_tags = True
image/views.py
from django.views.generic import ListView, DetailView

from eventlog.models import Log

from .models import Image

class ActivityMixin(object):
    def get_context_data(self, kwargs):
        context = super(ActivityMixin, self).get_context_data(**kwargs)
        context['activities'] = Log.objects.filter(user=self.request.user)
        return context


class IndexListView(ActivityMixin, ListView):
    template_name = 'image/index.html'
    model = Image
    context_object_name = 'images'
    queryset = Image.objects.all()
image/templates/image/index.html
<ul>
  {% for activity in activities %}
  <li>({{ activity.timestamp }}) - {{ activity.action }} [{{ activity.extra.title }}]</li>
  {% endfor %}
</ul>
comments powered by Disqus