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 disabled = getattr(form_class, 'disabled', False)
29 template = getattr(form_class, 'disabled_template', None)
31 return render(request, template, {'title': form_class.form_title})
34 contact = get_object_or_404(Contact, id=contact_id, form_tag=form_tag)
35 if form_tag != 'olimpiada':
37 if key != contact.key:
41 if request.method == 'POST':
42 form = form_class(request.POST, request.FILES, instance=contact)
44 form = form_class(initial=request.GET, instance=contact)
45 if request.method == 'POST':
46 formsets = form.get_formsets(request)
47 if form.is_valid() and all(formset.is_valid() for formset in formsets.itervalues()):
48 contact = form.save(request, formsets.values())
50 return redirect('contact_results', contact.id, contact.digest())
52 return redirect('contact_thanks', form_tag)
54 formsets = form.get_formsets()
57 request, ['contact/%s/form.html' % form_tag, 'contact/form.html'],
58 {'form': form, 'formsets': formsets, 'formset_errors': any(formset.errors for formset in formsets.values())}
62 def thanks(request, form_tag):
64 form_class = contact_forms[form_tag]
69 request, ['contact/%s/thanks.html' % form_tag, 'contact/thanks.html'],
70 {'base_template': getattr(form_class, 'base_template', None)})
73 def results(request, contact_id, digest):
74 contact = get_object_or_404(Contact, id=contact_id)
75 if digest != contact.digest():
78 form_class = contact_forms[contact.form_tag]
83 request, 'contact/%s/results.html' % contact.form_tag,
85 'results': form_class.results(contact),
86 'base_template': getattr(form_class, 'base_template', None),
91 @permission_required('contact.change_attachment')
92 def attachment(request, contact_id, tag):
93 attachment = get_object_or_404(Attachment, contact_id=contact_id, tag=tag)
94 attachment_url = unquote(attachment.file.url)
95 return serve_file(attachment_url)