/
views.py
415 lines (325 loc) · 12.8 KB
/
views.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import abc
import json
import re
import requests
from django.conf import settings
from django.contrib.gis.geos import Point
from django.core.urlresolvers import reverse
from django.core.validators import validate_email
from django.forms import ValidationError
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404
from django.views.generic import FormView, DetailView, TemplateView
from django.utils import translation
from django.utils.translation import ugettext as _
from councils.models import Council
from data_finder.models import (
LoggedPostcode,
CampaignSignup,
ElectionNotificationSignup
)
from pollingstations.models import (
PollingStation,
ResidentialAddress,
CustomFinder
)
from whitelabel.views import WhiteLabelTemplateOverrideMixin
from .forms import PostcodeLookupForm, AddressSelectForm
from .helpers import (
AddressSorter,
DirectionsHelper,
geocode,
EveryElectionWrapper,
MultipleCouncilsException,
PostcodeError,
RateLimitError,
RoutingHelper
)
class LogLookUpMixin(object):
def log_postcode(self, postcode, context, view_used):
if 'language' in context:
language = context['language']
else:
language = self.get_language()
if 'brand' in context:
brand = context['brand']
else:
brand = self.request.brand
kwargs = {
'postcode': postcode,
'had_data': bool(context['we_know_where_you_should_vote']),
'location': context['location'],
'council': context['council'],
'brand': brand,
'language': language,
'view_used': view_used,
}
kwargs.update(self.request.session['utm_data'])
LoggedPostcode.objects.create(**kwargs)
class LanguageMixin(object):
def get_language(self):
if self.request.session and\
translation.LANGUAGE_SESSION_KEY in self.request.session and\
self.request.session[translation.LANGUAGE_SESSION_KEY]:
return self.request.session[translation.LANGUAGE_SESSION_KEY]
else:
return ''
class HomeView(WhiteLabelTemplateOverrideMixin, FormView):
form_class = PostcodeLookupForm
template_name = "home.html"
def form_valid(self, form):
postcode = form.cleaned_data['postcode'].replace(' ', '')
rh = RoutingHelper(postcode)
endpoint = rh.get_endpoint()
self.success_url = reverse(
endpoint.view,
kwargs=endpoint.kwargs
)
return super(HomeView, self).form_valid(form)
def form_invalid(self, form):
context = self.get_context_data(form=form)
context['postcode'] = form.data.get('postcode', '')
return self.render_to_response(context)
class PrivacyView(WhiteLabelTemplateOverrideMixin, TemplateView):
template_name = "privacy.html"
class BasePollingStationView(
TemplateView, LogLookUpMixin, LanguageMixin, metaclass=abc.ABCMeta):
template_name = "postcode_view.html"
@abc.abstractmethod
def get_location(self):
pass
@abc.abstractmethod
def get_council(self):
pass
@abc.abstractmethod
def get_station(self):
pass
def get_directions(self):
if self.location and self.station and self.station.location:
dh = DirectionsHelper()
return dh.get_directions(
start_location=self.location,
end_location=self.station.location,
)
else:
return None
def get_context_data(self, **context):
context['tile_layer'] = settings.TILE_LAYER
context['mq_key'] = settings.MQ_KEY
try:
l = self.get_location()
except (PostcodeError, RateLimitError) as e:
context['error'] = str(e)
return context
if l is None:
# AddressView.get_location() may legitimately return None
self.location = None
else:
self.location = Point(l['wgs84_lon'], l['wgs84_lat'])
self.gss_codes = l['gss_codes']
self.council_gss = l['council_gss']
self.council = self.get_council()
self.station = self.get_station()
self.directions = self.get_directions()
ee = EveryElectionWrapper(self.postcode)
context['has_election'] = ee.has_election()
if not context['has_election']:
context['error'] = 'There are no upcoming elections in your area'
context['election_explainers'] = ee.get_explanations()
context['postcode'] = self.postcode
context['location'] = self.location
context['council'] = self.council
context['station'] = self.station
context['directions'] = self.directions
context['we_know_where_you_should_vote'] = self.station
context['noindex'] = True
if not context['we_know_where_you_should_vote']:
if l is None:
context['custom'] = None
else:
context['custom'] = CustomFinder.objects.get_custom_finder(
l['gss_codes'], self.postcode)
self.log_postcode(self.postcode, context, type(self).__name__)
return context
class PostcodeView(BasePollingStationView):
def get(self, request, *args, **kwargs):
if 'postcode' in request.GET:
self.kwargs['postcode'] = kwargs['postcode'] = request.GET['postcode']
if 'postcode' not in kwargs or kwargs['postcode'] == '':
return HttpResponseRedirect(reverse('home'))
self.kwargs['postcode'] = kwargs['postcode'] = kwargs['postcode'].upper().replace(' ', '')
rh = RoutingHelper(self.kwargs['postcode'])
endpoint = rh.get_endpoint()
if endpoint.view != 'postcode_view':
return HttpResponseRedirect(
reverse(endpoint.view, kwargs=endpoint.kwargs)
)
else:
# we are already in postcode_view
self.postcode = kwargs['postcode']
try:
context = self.get_context_data(**kwargs)
except MultipleCouncilsException:
return HttpResponseRedirect(
reverse('multiple_councils_view',
kwargs={'postcode': self.postcode})
)
return self.render_to_response(context)
def get_location(self):
return geocode(self.postcode)
def get_council(self):
if getattr(self, 'council_gss'):
try:
return Council.objects.defer("area", "location").get(
council_id=self.council_gss)
except Council.DoesNotExist:
pass
if getattr(self, 'gss_codes'):
try:
return Council.objects.defer("area", "location").get(
council_id__in=self.gss_codes)
except Council.DoesNotExist:
pass
return Council.objects.get(
area__covers=self.location)
def get_station(self):
return PollingStation.objects.get_polling_station(
self.council.council_id, location=self.location)
class AddressView(BasePollingStationView):
def get(self, request, *args, **kwargs):
self.address = get_object_or_404(
ResidentialAddress,
slug=self.kwargs['address_slug']
)
self.postcode = self.address.postcode
try:
context = self.get_context_data(**kwargs)
except MultipleCouncilsException:
return HttpResponseRedirect(
reverse('multiple_councils_view',
kwargs={'postcode': self.postcode})
)
return self.render_to_response(context)
def get_location(self):
try:
location = geocode(self.postcode)
return location
except PostcodeError:
return None
def get_council(self):
return Council.objects.defer("area", "location").get(
pk=self.address.council_id)
def get_station(self):
if not self.address.polling_station_id:
return None
return PollingStation.objects.get_polling_station_by_id(
self.address.polling_station_id,
self.address.council_id)
class WeDontKnowView(PostcodeView):
def get(self, request, *args, **kwargs):
self.postcode = kwargs['postcode']
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_station(self):
return None
class MultipleCouncilsView(TemplateView, LogLookUpMixin, LanguageMixin):
# because sometimes "we don't know" just isn't uncertain enough
template_name = "multiple_councils.html"
def get(self, request, *args, **kwargs):
rh = RoutingHelper(self.kwargs['postcode'])
endpoint = rh.get_endpoint()
if endpoint.view != 'multiple_councils_view':
return HttpResponseRedirect(
reverse(endpoint.view, kwargs=endpoint.kwargs)
)
self.council_ids = rh.councils
context = self.get_context_data(**kwargs)
return self.render_to_response(context)
def get_context_data(self, **context):
context['councils'] = []
for council_id in self.council_ids:
context['councils'].append(Council.objects.get(pk=council_id))
log_data = {
'we_know_where_you_should_vote': False,
'location': None,
'council': None,
}
self.log_postcode(self.kwargs['postcode'], log_data, type(self).__name__)
return context
def signup(request, postcode, model, fields):
if request.POST.get('join', 'false') == 'true':
join_list = True
else:
join_list = False
name = request.POST.get('name', '')
email = request.POST.get('email', '')
errors = { 'errors': { 'name': 0, 'email': 0 } }
if 'name' in fields:
if not name or len(name) > 100:
errors['errors']['name'] = 1
if 'email' in fields:
if not email or len(email) > 100:
errors['errors']['email'] = 1
try:
validate_email(email)
except ValidationError:
errors['errors']['email'] = 1
if (errors['errors']['name'] == 1 and 'name' in fields) or\
(errors['errors']['email'] == 1 and 'email' in fields):
return HttpResponse(json.dumps(errors),
status=400, content_type='application/json')
kwargs = { 'postcode': postcode, 'join_list': join_list }
if 'name' in fields:
kwargs['name'] = name
if 'email' in fields:
kwargs['email'] = email
model.objects.create(**kwargs)
return HttpResponse(json.dumps(errors),
status=200, content_type='application/json')
def election_notification_signup(request, postcode):
return signup(request, postcode, ElectionNotificationSignup, ['email'])
def campaign_signup(request, postcode):
return signup(request, postcode, CampaignSignup, ['name', 'email'])
class AddressFormView(FormView):
form_class = AddressSelectForm
template_name = "address_select.html"
def get_context_data(self, **kwargs):
context = super(AddressFormView, self).get_context_data(**kwargs)
context['noindex'] = True
return context
def get_form(self, form_class):
addresses = ResidentialAddress.objects.filter(
postcode=self.kwargs['postcode']
)
if not addresses:
raise Http404
sorter = AddressSorter(addresses)
addresses = sorter.natural_sort()
select_addresses = [(element.slug, element.address) for element in addresses]
return form_class(select_addresses, self.kwargs['postcode'], **self.get_form_kwargs())
def form_valid(self, form):
self.success_url = reverse(
'address_view',
kwargs={'address_slug': form.cleaned_data['address']}
)
return super(AddressFormView, self).form_valid(form)
class CoverageView(TemplateView):
template_name = 'coverage.html'
def get_context_data(self, *a, **k):
context = super(CoverageView, self).get_context_data(*a, **k)
num_councils = Council.objects.count()
districts, stations = 0, 0
covered = []
for council in Council.objects.all():
if council.pollingstation_set.count() > 1:
stations += 1
covered.append(council)
if council.pollingdistrict_set.count() > 1:
districts += 1
context['num_councils'] = num_councils
context['num_district_councils'] = districts
context['perc_districts'] = "%d%%" % (float(districts) / num_councils * 100)
context['num_station_councils'] = stations
context['perc_stations'] = "%d%%" % (float(stations) / num_councils * 100)
context['covered'] = covered
return context