e52b6b2888733909936e3a4d9175e688a45572ab
[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 .forms import contact_forms
9 from .models import Attachment
10
11
12 def form(request, form_tag, force_enabled=False):
13     try:
14         form_class = contact_forms[form_tag]
15     except KeyError:
16         raise Http404
17     if (getattr(form_class, 'disabled', False) and
18             not (force_enabled and request.user.is_superuser)):
19         template = getattr(form_class, 'disabled_template', None)
20         if template:
21             return render(request, template, {'title': form_class.form_title})
22         raise Http404
23     if request.method == 'POST':
24         form = form_class(request.POST, request.FILES)
25         formsets = []
26         valid = form.is_valid()
27         for formset in getattr(form, 'form_formsets', ()):
28             fset = formset(request.POST, request.FILES)
29             if not fset.is_valid():
30                 valid = False
31             formsets.append(fset)
32         if valid:
33             form.save(request, formsets)
34             return redirect('contact_thanks', form_tag)
35     else:
36         form = form_class(initial=request.GET)
37         formsets = []
38         for formset in getattr(form, 'form_formsets', ()):
39             formsets.append(formset())
40     return render(
41         request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
42         {'form': form, 'formsets': formsets}
43     )
44
45
46 def thanks(request, form_tag):
47     try:
48         form_class = contact_forms[form_tag]
49     except KeyError:
50         raise Http404
51
52     return render(
53         request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
54         {'base_template': getattr(form_class, 'base_template', None)})
55
56
57 @permission_required('contact.change_attachment')
58 def attachment(request, contact_id, tag):
59     attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
60     attachment_url = unquote(attachment.file.url)
61     return serve_file(attachment_url)