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 django.views.decorators.cache import never_cache
8 from fnpdjango.utils.views import serve_file
9 from honeypot.decorators import check_honeypot
11 from .forms import contact_forms, update_forms
12 from .models import Attachment, Contact
17 def form(request, form_tag, force_enabled=False, contact_id=None, key=None):
18 update = bool(contact_id and key)
20 if update and form_tag in update_forms:
21 form_class = update_forms[form_tag]
23 form_class = contact_forms[form_tag]
26 if not (force_enabled and request.user.is_superuser):
27 if form_class.is_disabled():
28 template = form_class.disabled_template
30 return render(request, template, {'title': form_class.form_title})
33 contact = get_object_or_404(Contact, id=contact_id, form_tag=form_tag)
34 if not form_class.updatable:
36 if key != contact.key:
40 if request.method == 'POST':
41 form = form_class(request.POST, request.FILES, instance=contact)
43 form = form_class(initial=request.GET, instance=contact)
44 if request.method == 'POST':
45 formsets = form.get_formsets(request)
46 if form.is_valid() and all(formset.is_valid() for formset in formsets.itervalues()):
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 = form.get_formsets()
56 request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
57 {'form': form, 'formsets': formsets, 'formset_errors': any(formset.errors for formset in formsets.values())}
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)
97 def attachment_key(request, contact_id, tag, key):
98 contact = Contact.objects.get(id=contact_id)
99 if key != contact.key:
101 attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
102 attachment_url = unquote(attachment.file.url)
103 return serve_file(attachment_url)