Sending emails with contest keys
[edumed.git] / contact / views.py
1 from django.contrib.auth.decorators import permission_required
2 from django.http import Http404, HttpResponse
3 from django.shortcuts import get_object_or_404, redirect, render
4 from django.utils.translation import ugettext_lazy as _
5 from fnpdjango.utils.views import serve_file
6 from .forms import contact_forms
7 from .models import Attachment
8
9
10 def form(request, form_tag):
11     try:
12         form_class = contact_forms[form_tag]
13     except KeyError:
14         raise Http404
15     if request.method == 'POST':
16         form = form_class(request.POST, request.FILES)
17         formsets = []
18         valid = form.is_valid()
19         for formset in getattr(form, 'form_formsets', ()):
20             fset = formset(request.POST, request.FILES)
21             if not fset.is_valid():
22                 valid = False
23             formsets.append(fset)
24         if valid:
25             form.save(request, formsets)
26             return redirect('contact_thanks', form_tag)
27     else:
28         form = form_class(initial=request.GET)
29         formsets = []
30         for formset in getattr(form, 'form_formsets', ()):
31             formsets.append(formset())
32     return render(request,
33                 ['contact/%s/form.html' % form_tag, 'contact/form.html'],
34                 {'form': form, 'formsets': formsets}
35             )
36
37
38 def thanks(request, form_tag):
39     try:
40         form_class = contact_forms[form_tag]
41     except KeyError:
42         raise Http404
43
44     return render(request,
45                 ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
46                 dict(base_template = getattr(form_class, 'base_template', None))
47             )
48
49
50 @permission_required('contact.change_attachment')
51 def attachment(request, contact_id, tag):
52     attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
53     return serve_file(attachment.file.url)