1 # -*- coding: utf-8 -*-
2 from urllib import unquote
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 fnpdjango.utils.views import serve_file
8 from honeypot.decorators import check_honeypot
10 from .forms import contact_forms
11 from .models import Attachment
15 def form(request, form_tag, force_enabled=False):
17 form_class = contact_forms[form_tag]
20 if (getattr(form_class, 'disabled', False) and
21 not (force_enabled and request.user.is_superuser)):
22 template = getattr(form_class, 'disabled_template', None)
24 return render(request, template, {'title': form_class.form_title})
26 if request.method == 'POST':
27 form = form_class(request.POST, request.FILES)
29 form = form_class(initial=request.GET)
30 formset_classes = getattr(form, 'form_formsets', {})
31 if request.method == 'POST':
33 prefix: formset_class(request.POST, request.FILES, prefix=prefix)
34 for prefix, formset_class in formset_classes.iteritems()}
35 if form.is_valid() and all(formset.is_valid() for formset in formsets.itervalues()):
36 form.save(request, formsets.values())
37 return redirect('contact_thanks', form_tag)
39 formsets = {prefix: formset_class(prefix=prefix) for prefix, formset_class in formset_classes.iteritems()}
42 request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
43 {'form': form, 'formsets': formsets}
47 def thanks(request, form_tag):
49 form_class = contact_forms[form_tag]
54 request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
55 {'base_template': getattr(form_class, 'base_template', None)})
58 @permission_required('contact.change_attachment')
59 def attachment(request, contact_id, tag):
60 attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
61 attachment_url = unquote(attachment.file.url)
62 return serve_file(attachment_url)