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