1 # -*- coding: utf-8 -*-
2 from urllib import unquote
4 from datetime import datetime
5 from django.contrib.auth.decorators import permission_required
6 from django.http import Http404
7 from django.shortcuts import get_object_or_404, redirect, render
8 from django.utils import timezone
9 from django.views.decorators.cache import never_cache
10 from fnpdjango.utils.views import serve_file
11 from honeypot.decorators import check_honeypot
13 from edumed.utils import localtime_to_utc
14 from .forms import contact_forms
15 from .models import Attachment
20 def form(request, form_tag, force_enabled=False):
22 form_class = contact_forms[form_tag]
25 if not (force_enabled and request.user.is_superuser):
26 disabled = getattr(form_class, 'disabled', False)
27 end_tuple = getattr(form_class, 'ends_on')
28 end_time = localtime_to_utc(datetime(*end_tuple)) if end_tuple else None
29 expired = end_time and end_time < timezone.now()
30 if disabled or expired:
31 template = getattr(form_class, 'disabled_template', None)
33 return render(request, template, {'title': form_class.form_title})
35 if request.method == 'POST':
36 form = form_class(request.POST, request.FILES)
38 form = form_class(initial=request.GET)
39 formset_classes = getattr(form, 'form_formsets', {})
40 if request.method == 'POST':
42 prefix: formset_class(request.POST, request.FILES, prefix=prefix)
43 for prefix, formset_class in formset_classes.iteritems()}
44 if form.is_valid() and all(formset.is_valid() for formset in formsets.itervalues()):
45 form.save(request, formsets.values())
46 return redirect('contact_thanks', form_tag)
48 formsets = {prefix: formset_class(prefix=prefix) for prefix, formset_class in formset_classes.iteritems()}
51 request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
52 {'form': form, 'formsets': formsets}
56 def thanks(request, form_tag):
58 form_class = contact_forms[form_tag]
63 request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
64 {'base_template': getattr(form_class, 'base_template', None)})
67 @permission_required('contact.change_attachment')
68 def attachment(request, contact_id, tag):
69 attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
70 attachment_url = unquote(attachment.file.url)
71 return serve_file(attachment_url)