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 wolnelektury.utils import localtime_to_utc
14 from .forms import contact_forms
15 from .models import Attachment, Contact
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', None)
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 contact = form.save(request, formsets.values())
47 return redirect('contact_results', contact.id, contact.digest())
49 return redirect('contact_thanks', form_tag)
51 formsets = {prefix: formset_class(prefix=prefix) for prefix, formset_class in formset_classes.iteritems()}
54 request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
55 {'form': form, 'formsets': formsets}
59 def thanks(request, form_tag):
61 form_class = contact_forms[form_tag]
66 request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
67 {'base_template': getattr(form_class, 'base_template', None)})
70 def results(request, contact_id, digest):
71 contact = get_object_or_404(Contact, id=contact_id)
72 if digest != contact.digest():
75 form_class = contact_forms[contact.form_tag]
80 request, 'contact/%s/results.html' % contact.form_tag,
82 'results': form_class.results(contact),
83 'base_template': getattr(form_class, 'base_template', None),
88 @permission_required('contact.change_attachment')
89 def attachment(request, contact_id, tag):
90 attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
91 attachment_url = unquote(attachment.file.url)
92 return serve_file(attachment_url)