tickets: Send a confirmation email for bookings.
[matthijs/projects/dorestad-bookings.git] / tickets / views.py
1 # Create your views here.
2
3 import django
4 from django.shortcuts import render_to_response
5
6 from models import Booking
7
8 class BookingForm(django.forms.ModelForm):
9     class Meta:
10         model=Booking
11
12 def confirm_booking(booking):
13     from django.core.mail import EmailMessage
14
15     context = {'booking' : booking}
16
17     rendered = django.template.loader.render_to_string('tickets/booked.eml', context)
18     (headers, body) = rendered.strip().split('\n\n', 1)
19
20     # Turn the headers into a dict so EmailMessage can turn them into a
21     # string again. Bit pointless, but it works. 
22     # Perhaps we should just use python email stuff directly. OTOH, we
23     # still always need to parse for the From header.
24
25     headers_dict = {}
26     # If no From header is present, let EmailMessage do the default
27     # thing
28     from_email = None
29     for header in headers.split('\n'):
30         (field, value) = header.split(':')
31         if (field == 'From'):
32             from_email = value
33         elif (field == 'Subject'):
34             subject = value
35         else:
36             # Don't put From and Subject in the dict, else they'll be
37             # present twice.
38             headers_dict[field] = value
39
40     msg = EmailMessage(
41         # Only setting the From address through headers won't set the
42         # envelope address right.
43         from_email = from_email,
44         subject    = subject,
45         body       = body,
46         to         = [booking.email],
47         headers    = headers_dict
48     )
49     msg.send()
50
51 def book(request):
52     if request.method == "POST":
53         f = BookingForm(request.POST)
54     else:
55         f = BookingForm()
56
57     if f.is_valid():
58         booking = f.save()
59         confirm_booking(booking)
60         return render_to_response('tickets/booked.html', {'booking' : booking})
61
62     return render_to_response('tickets/bookingform.html', {'form' : f})