view madeira/email_list/views.py @ 52:7f9e76e7eb4d

For issue #7, another commit for a mailing list application. In this commit we add to the tests to check for the confirmation email. Also realized the request coming from the email is a GET, not a POST.
author Brian Neal <bgneal@gmail.com>
date Thu, 29 Mar 2012 20:01:13 -0500
parents 13b2561c909d
children
line wrap: on
line source
"""
Views for the email_list application.

"""
import logging

from django.http import HttpResponseServerError
from django.shortcuts import render, redirect, get_object_or_404

from email_list.forms import SubscriberForm
from email_list.models import Subscriber


logger = logging.getLogger(__name__)


def mailing_list(request):
    """
    The main view for handling email list actions (subscribe or unsubscribe).

    """
    if request.method == 'POST':
        form = SubscriberForm(request.POST)
        if form.is_valid():
            form.process()

            if form.is_subscribe():
                return redirect('email_list-request_subscribe')
            else:
                return redirect('email_list-request_unsubscribe')

    else:
        form = SubscriberForm()

    return render(request, 'email_list/subscribe_form.html', {'form': form})


def confirm(request, key):
    """
    This view handles the confirmation of a subscribe or unsubscribe action.

    """
    subscriber = get_object_or_404(Subscriber, key=key)

    if subscriber.is_pending():
        subscriber.set_active()
        subscriber.save()
        return redirect('email_list-subscribed')
    elif subscriber.is_leaving():
        subscriber.delete()
        return redirect('email_list-unsubscribed')

    # This should not happen
    logger.error("Trying to confirm subscriber %d, but status is %s",
            subscriber.pk, subscriber.status)
    return HttpResponseServerError()