b9a411fd160e1c46da241df7ec7238b1865b6f5b
[edumed.git] / contact / views.py
1 # -*- coding: utf-8 -*-
2 from urllib import unquote
3
4 from django.contrib.auth.decorators import permission_required
5 from django.http import Http404
6 from django.shortcuts import get_object_or_404, redirect, render
7 from fnpdjango.utils.views import serve_file
8 from honeypot.decorators import check_honeypot
9
10 from .forms import contact_forms
11 from .models import Attachment
12
13
14 @check_honeypot
15 def form(request, form_tag, force_enabled=False):
16     try:
17         form_class = contact_forms[form_tag]
18     except KeyError:
19         raise Http404
20     if (getattr(form_class, 'disabled', False) and
21             not (force_enabled and request.user.is_superuser)):
22         template = getattr(form_class, 'disabled_template', None)
23         if template:
24             return render(request, template, {'title': form_class.form_title})
25         raise Http404
26     if request.method == 'POST':
27         form = form_class(request.POST, request.FILES)
28         formsets = []
29         valid = form.is_valid()
30         for formset in getattr(form, 'form_formsets', ()):
31             fset = formset(request.POST, request.FILES)
32             if not fset.is_valid():
33                 valid = False
34             formsets.append(fset)
35         if valid:
36             form.save(request, formsets)
37             return redirect('contact_thanks', form_tag)
38     else:
39         form = form_class(initial=request.GET)
40         formsets = []
41         for formset in getattr(form, 'form_formsets', ()):
42             formsets.append(formset())
43     return render(
44         request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
45         {'form': form, 'formsets': formsets}
46     )
47
48
49 def thanks(request, form_tag):
50     try:
51         form_class = contact_forms[form_tag]
52     except KeyError:
53         raise Http404
54
55     return render(
56         request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
57         {'base_template': getattr(form_class, 'base_template', None)})
58
59
60 @permission_required('contact.change_attachment')
61 def attachment(request, contact_id, tag):
62     attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
63     attachment_url = unquote(attachment.file.url)
64     return serve_file(attachment_url)