1 # This file is part of Wolnelektury, licensed under GNU Affero GPLv3 or later.
2 # Copyright © Fundacja Nowoczesna Polska. See NOTICE for more information.
4 from urllib.parse import unquote
6 from datetime import datetime
7 from django.contrib.auth.decorators import permission_required
8 from django.http import Http404
9 from django.shortcuts import get_object_or_404, redirect, render
10 from django.utils import timezone
11 from django.views.decorators.cache import never_cache
12 from fnpdjango.utils.views import serve_file
13 from honeypot.decorators import check_honeypot
15 from wolnelektury.utils import localtime_to_utc
16 from .forms import contact_forms
17 from .models import Attachment, Contact
22 def form(request, form_tag, force_enabled=False):
24 form_class = contact_forms[form_tag]
27 if not (force_enabled and request.user.is_superuser):
28 disabled = getattr(form_class, 'disabled', False)
29 end_tuple = getattr(form_class, 'ends_on', None)
30 end_time = localtime_to_utc(datetime(*end_tuple)) if end_tuple else None
31 expired = end_time and end_time < timezone.now()
32 if disabled or expired:
33 template = getattr(form_class, 'disabled_template', None)
35 return render(request, template, {'title': form_class.form_title})
37 if request.method == 'POST':
38 form = form_class(request.POST, request.FILES)
40 form = form_class(initial=request.GET)
41 formset_classes = getattr(form, 'form_formsets', {})
42 if request.method == 'POST':
44 prefix: formset_class(request.POST, request.FILES, prefix=prefix)
45 for prefix, formset_class in formset_classes.items()}
46 if form.is_valid() and all(formset.is_valid() for formset in formsets.values()):
47 contact = form.save(request, formsets.values())
49 return redirect('contact_results', contact.id, contact.digest())
51 return redirect('contact_thanks', form_tag)
53 formsets = {prefix: formset_class(prefix=prefix) for prefix, formset_class in formset_classes.items()}
56 request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
57 {'form': form, 'formsets': formsets}
61 def thanks(request, form_tag):
63 form_class = contact_forms[form_tag]
68 request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
69 {'base_template': getattr(form_class, 'base_template', None)})
72 def results(request, contact_id, digest):
73 contact = get_object_or_404(Contact, id=contact_id)
74 if digest != contact.digest():
77 form_class = contact_forms[contact.form_tag]
82 request, 'contact/%s/results.html' % contact.form_tag,
84 'results': form_class.results(contact),
85 'base_template': getattr(form_class, 'base_template', None),
90 @permission_required('contact.change_attachment')
91 def attachment(request, contact_id, tag):
92 attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
93 attachment_url = unquote(attachment.file.url)
94 return serve_file(attachment_url)