January 23rd 2015

Slack integration for Django

I recently started using the Slack group chat tool in a few teams. Wishing to add some vanity notifications such as sales and user growth milestones from some Django-based projects, I put together an easy-to-use integration between the two called django-slack.

Whilst you can use any generic Python-based method of sending messages to Slack, using a Django-specific integration has some advantages:


Here is an example of how to send a message from a Django view:

from django_slack import slack_message

@login_required
def view(request, item_id):
    item = get_object_or_404(Item, pk=item_id)

    slack_message('items/viewed.slack', {
        'item': item,
        'user': request.user,
    })

    return render(request, 'items/view.html', {
        'item': item,
    })

Where items/viewed.slack (in your templates directory) might contain:

{% extends django_slack %}

{% block text %}
{{ user.get_full_name }} just viewed {{ item.title }} ({{ item.content|urlize }}).
{% endblock %}

.slack files are regular Django templates — text is automatically escaped as appropriate and that you can use the regular template filters and tags such as urlize, loops, etc.

By default, django-slack posts to the #general channel, but it can be overridden on a per-message basis by specifying a channel block:

{% block channel %}
#mychannel
{% endblock %}

You can also set the icon, URL and emoji in a similar fashion. You can set global defaults for all of these attributes to avoid DRY violations within .slack templates as well.

For more information please see the project homepage or read the documentation. Patches and other contributions are welcome via the django-slack GitHub project.




You can subscribe to new posts via email or RSS.