1 from urllib.parse import unquote
3 from datetime import datetime
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 django.utils import timezone
8 from django.views.decorators.cache import never_cache
9 from fnpdjango.utils.views import serve_file
10 from honeypot.decorators import check_honeypot
12 from wolnelektury.utils import localtime_to_utc
13 from .forms import contact_forms
14 from .models import Attachment, Contact
19 def form(request, form_tag, force_enabled=False):
21 form_class = contact_forms[form_tag]
24 if not (force_enabled and request.user.is_superuser):
25 disabled = getattr(form_class, 'disabled', False)
26 end_tuple = getattr(form_class, 'ends_on', None)
27 end_time = localtime_to_utc(datetime(*end_tuple)) if end_tuple else None
28 expired = end_time and end_time < timezone.now()
29 if disabled or expired:
30 template = getattr(form_class, 'disabled_template', None)
32 return render(request, template, {'title': form_class.form_title})
34 if request.method == 'POST':
35 form = form_class(request.POST, request.FILES)
37 form = form_class(initial=request.GET)
38 formset_classes = getattr(form, 'form_formsets', {})
39 if request.method == 'POST':
41 prefix: formset_class(request.POST, request.FILES, prefix=prefix)
42 for prefix, formset_class in formset_classes.items()}
43 if form.is_valid() and all(formset.is_valid() for formset in formsets.itervalues()):
44 contact = form.save(request, formsets.values())
46 return redirect('contact_results', contact.id, contact.digest())
48 return redirect('contact_thanks', form_tag)
50 formsets = {prefix: formset_class(prefix=prefix) for prefix, formset_class in formset_classes.items()}
53 request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
54 {'form': form, 'formsets': formsets}
58 def thanks(request, form_tag):
60 form_class = contact_forms[form_tag]
65 request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
66 {'base_template': getattr(form_class, 'base_template', None)})
69 def results(request, contact_id, digest):
70 contact = get_object_or_404(Contact, id=contact_id)
71 if digest != contact.digest():
74 form_class = contact_forms[contact.form_tag]
79 request, 'contact/%s/results.html' % contact.form_tag,
81 'results': form_class.results(contact),
82 'base_template': getattr(form_class, 'base_template', None),
87 @permission_required('contact.change_attachment')
88 def attachment(request, contact_id, tag):
89 attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
90 attachment_url = unquote(attachment.file.url)
91 return serve_file(attachment_url)