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