Commit 00436026 authored by okhin's avatar okhin

Merge branch 'django-1.8' into 'master'

Django 1.8 - Class Based view

Class Basd view wherever it was possible. The code is a bit cleaner now.

See merge request !4
parents dccf375b 849b1779
from forms import AddViolation, SearchViolation from forms import AddViolation, SearchViolation
from django.views.generic import ListView, FormView, DetailView
from django.views.generic.list import MultipleObjectMixin
from django.http import HttpResponse, HttpResponseRedirect, Http404 from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext, loader, Context from django.template import RequestContext, loader, Context
...@@ -12,6 +14,7 @@ from django.contrib import messages ...@@ -12,6 +14,7 @@ from django.contrib import messages
from django.contrib.auth.models import User from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.db.models import Count from django.db.models import Count
from haystack.generic_views import SearchView
from models import Violation, Attachment, Comment, Confirmation, COUNTRIES, STATUS, Operator from models import Violation, Attachment, Comment, Confirmation, COUNTRIES, STATUS, Operator
from tempfile import mkstemp from tempfile import mkstemp
from datetime import datetime from datetime import datetime
...@@ -138,14 +141,26 @@ def sendverifymail(service,to,body): ...@@ -138,14 +141,26 @@ def sendverifymail(service,to,body):
return actid return actid
def add(request): class JSONMixin(object):
if request.method == 'POST': def get(self, request, *args, **kwargs):
form = AddViolation(request.POST) qs = self.get_queryset()
if form.is_valid(): if qs.count():
msg=_("Thank you for submitting a new report. To finalize your submission please confirm using your validation key.\nYour verification key is %s/%s%s\nPlease note that reports are moderated, it might take some time before your report appears online. Thank you for your patience.") return HttpResponse(json.dumps(sorted([(x.object.id, x.object.resource_name) for x in qs])))
actid=sendverifymail('activate?key=',form.cleaned_data['email'], msg) else:
operator, created = Operator.objects.get_or_create(name=form.cleaned_data['operator']) return HttpResponse('')
v=Violation(
class AddForm(FormView):
model = Violation
template_name = 'index.html'
form_class = AddViolation
success_url = '/'
context_object_name = 'violations'
def form_valid(self, form):
msg=_("Thank you for submitting a new report. To finalize your submission please confirm using your validation key.\nYour verification key is %s/%s%s\nPlease note that reports are moderated, it might take some time before your report appears online. Thank you for your patience.")
actid=sendverifymail('activate?key=',form.cleaned_data['email'], msg)
operator, created = Operator.objects.get_or_create(name=form.cleaned_data['operator'])
v=Violation(
country = form.cleaned_data['country'], country = form.cleaned_data['country'],
operator_ref = operator, operator_ref = operator,
contract = form.cleaned_data['contract'], contract = form.cleaned_data['contract'],
...@@ -159,108 +174,96 @@ def add(request): ...@@ -159,108 +174,96 @@ def add(request):
loophole = form.cleaned_data['loophole'], loophole = form.cleaned_data['loophole'],
activationid = actid activationid = actid
) )
v.save() v.save()
#c=Confirmation(key='', email=form.cleaned_data['email'], violation=v) #c=Confirmation(key='', email=form.cleaned_data['email'], violation=v)
#c.save() #c.save()
c = Comment( c = Comment(
comment=form.cleaned_data['comment'], comment=form.cleaned_data['comment'],
submitter_email=form.cleaned_data['email'], submitter_email=form.cleaned_data['email'],
submitter_name=form.cleaned_data['nick'], submitter_name=form.cleaned_data['nick'],
consent=form.cleaned_data['consent'], consent=form.cleaned_data['consent'],
timestamp=datetime.now(), timestamp=datetime.now(),
violation=v, violation=v,
) )
c.save() c.save()
for f in request.FILES.getlist('attachments[]'): for f in request.FILES.getlist('attachments[]'):
a=Attachment(comment=c, name=f.name, type=f.content_type) a=Attachment(comment=c, name=f.name, type=f.content_type)
m = hashlib.sha256() m = hashlib.sha256()
for chunk in f.chunks(): for chunk in f.chunks():
m.update(chunk) m.update(chunk)
sname=m.hexdigest() sname=m.hexdigest()
a.storage.save(sname,f) a.storage.save(sname,f)
a.save() a.save()
messages.add_message(request, messages.INFO, _('Thank you for submitting this report, you will receive a verification email immediately, if not check your spam folder.'))
messages.add_message(request, messages.INFO, _('Thank you for submitting this report, you will receive a verification email immediately, if not check your spam folder.')) return super(AddForm, self).form_valid(form)
return HttpResponseRedirect('/') # Redirect after POST
else:
form = AddViolation()
v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3]
return render_to_response(
'index.html',
{ 'form': form,
'violations': v_list },
context_instance=RequestContext(request))
# XXX obsoleted by API def get_queryset(self):
#def ajax(request, country=None, operator=None): return Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3]
# if not operator:
# return HttpResponse(json.dumps(sorted(list(set([x.operator for x in Violation.objects.filter(country=country,activationid='')])))))
# else:
# return HttpResponse(json.dumps(sorted(list(set([x.contract for x in Violation.objects.filter(country=country,activationid='',operator=operator)])))))
def index(request): def get_context_data(self, **kwargs):
v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3] context = super(AddForm, self).get_context_data(**kwargs)
form = AddViolation() reports = sorted([(i['total'],i['id'])
reports=sorted([(i['total'],i['id']) for i in Violation.objects.values('id').filter(activationid='').exclude(state__in=['closed', 'ooscope', 'duplicate']).annotate(total=Count('confirmation'))],
for i in Violation.objects.values('id').filter(activationid='').exclude(state__in=['closed', 'ooscope', 'duplicate']).annotate(total=Count('confirmation'))],
reverse=True) reverse=True)
# countries=sorted([(i['total'],i['country']) confirms = sorted([(i['total'],i['country'])
# for i in Violation.objects.values('country').filter(activationid='').annotate(total=Count('country'))], for i in Violation.objects.values('country').filter(activationid='').exclude(state__in=['closed', 'ooscope', 'duplicate']).annotate(total=Count('confirmation'))],
# reverse=True)
confirms=sorted([(i['total'],i['country'])
for i in Violation.objects.values('country').filter(activationid='').exclude(state__in=['closed', 'ooscope', 'duplicate']).annotate(total=Count('confirmation'))],
reverse=True) reverse=True)
operators=sorted([(i['total'],i['operator_ref__name']) operators = sorted([(i['total'],i['operator_ref__name'])
for i in Violation.objects.values('operator_ref__name').filter(activationid='').exclude(state__in=['closed', 'ooscope', 'duplicate']).annotate(total=Count('confirmation'))], for i in Violation.objects.values('operator_ref__name').filter(activationid='').exclude(state__in=['closed', 'ooscope', 'duplicate']).annotate(total=Count('confirmation'))],
reverse=True) reverse=True)
context['stats'] = [
(_('Total confirmed reorts'), len([i for i,z in reports if i>0])),
(_('Countries with some confirmed reports'), len([i for i,z in confirms if i>0])),
(_('Operators with some confirmed reports'), len([i for i,z in operators if i>0]))]
return context
return render_to_response( class ViolationsList(ListView):
'index.html', template_name = 'list.html'
{ 'form': form, context_object_name = 'violations'
'stats': [ (_('Total confirmed reports'), len([i for i,z in reports if i>0])),
(_('Countries with some confirmed reports'), len([i for i,z in confirms if i>0])),
(_('Operators with some confirmed reports'), len([i for i,z in operators if i>0])),
],
'violations': v_list },
context_instance=RequestContext(request))
def filter_violations(request, country, operator=None): def get_queryset(self):
if not operator: queryset = Violation.objects.filter(activationid='')
violations = Violation.objects.filter(activationid='', country=country) if 'operator' in self.kwargs:
if not violations.count(): # If i Have operator I have a country
violations = Violation.objects.filter(activationid='', operator_ref__name=country) queryset = Violation.objects.filter(activationid='',
else: country=self.kwargs['country'],
violations = Violation.objects.filter(activationid='', country=country, operator_ref__name=operator) operator_ref__name=self.kwargs['operator'])
if not request.GET.get('all'): if 'country' in self.kwargs:
violations = violations.exclude(state__in=['duplicate', 'closed']) queryset = Violation.objects.filter(activationid='',
return render_to_response('list.html', country=self.kwargs['country'])
{ "violations": violations, if 'all' not in self.request.GET:
"country": country, queryset = queryset.filter(activationid='').exclude(state__in=['duplicate', 'closed'])
"status": STATUS }, return queryset
context_instance=RequestContext(request))
def list_violations(request): def get_context_data(self, **kwargs):
violations = Violation.objects.filter(activationid='') context = super(ViolationsList, self).get_context_data(**kwargs)
if not request.GET.get('all'):
violations = violations.exclude(state__in=['duplicate', 'closed']) if 'country' in self.kwargs:
countries=sorted([(i['total'],i['country']) context['country'] = self.kwargs['country']
for i in Violation.objects.values('country').filter(activationid='').exclude(state__in=['duplicate', 'closed']).annotate(total=Count('country'))], else:
reverse=True) countries = sorted([(i['total'], i['country'])
countryweights=json.dumps([{'iso2': y, 'w': x} for x, y in countries]) for i in Violation.objects.values('country').filter(activationid='').exclude(state__in=['duplicate', 'closed']).annotate(total=Count('country'))],
return render_to_response('list.html', reverse=True)
{"violations": violations, countryweights=json.dumps([{'iso2': y, 'w': x} for x, y in countries])
"countries": dict([(y,x) for x,y in countries]), context['countries'] = countries
"countryweights": countryweights, context['countryweights'] = countryweights
"status": STATUS,}, return context
#"confirms": confirms,},
context_instance=RequestContext(request))
def view(request,id): class ViolationView(DetailView):
v = get_object_or_404(Violation, pk=id) model = Violation
if v.activationid: template_name = 'view.html'
raise Http404 pk_url_kwarg = 'id'
return render_to_response('view.html', { 'v': v, },context_instance=RequestContext(request)) context_object_name = 'v'
def get_object(self):
object = super(ViolationView, self).get_object()
if object.activationid:
raise Http404
return object
class LookupView(JSONMixin, SearchView):
queryset = Violation.objects.filter(activationid='')
form_class = SearchViolation
def get_attach(request,id): def get_attach(request,id):
f = get_object_or_404(Attachment, pk=id) f = get_object_or_404(Attachment, pk=id)
...@@ -270,15 +273,6 @@ def get_attach(request,id): ...@@ -270,15 +273,6 @@ def get_attach(request,id):
response['Content-Length'] = f.storage.size response['Content-Length'] = f.storage.size
return response return response
def lookup(request):
if request.method == 'GET':
form = SearchViolation(request.GET)
if form.is_valid():
v=form.search()
res=json.dumps(sorted([(x.object.id,x.object.resource_name) for x in v],reverse=True))
return HttpResponse(res)
return HttpResponse('')
def ascsv(request): def ascsv(request):
response = HttpResponse(mimetype='text/csv') response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=respectmynet.csv' response['Content-Disposition'] = 'attachment; filename=respectmynet.csv'
......
...@@ -122,5 +122,4 @@ ...@@ -122,5 +122,4 @@
{% endfor %} {% endfor %}
</tbody> </tbody>
</table> </table>
</div>
{%endblock%} {%endblock%}
...@@ -14,22 +14,22 @@ admin.autodiscover() ...@@ -14,22 +14,22 @@ admin.autodiscover()
urlpatterns = patterns('', urlpatterns = patterns('',
url(r'^$', url(r'^$',
view=bt.index, view=bt.AddForm.as_view(),
name="homepage"), name="homepage"),
url(r'^list/$', url(r'^list/$',
view=bt.list_violations, view=bt.ViolationsList.as_view(),
name="list_violations"), name="list_violations"),
url(r'^list/(?P<country>[^/]*)(/(?P<operator>[^/]*))?$', url(r'^list/(?P<country>\w+)/$',
view=bt.filter_violations, view=bt.ViolationsList.as_view(),
name="filter"), name="filter_country"),
url(r'^add/$', url(r'^list/(?P<country>\w+)/(?P<operator>\w+)/$',
view=bt.add, view=bt.ViolationsList.as_view(),
name="add_violation"), name="filter_operator"),
# violation cannonical url and redirections # violation cannonical url and redirections
url(r'^(?P<id>[0-9]*)$', url(r'^(?P<id>[0-9]*)$',
RedirectView.as_view(url='/view/%(id)s')), RedirectView.as_view(url='/view/%(id)s')),
url(r'^view/(?P<id>[0-9]*)$', url(r'^view/(?P<id>[0-9]*)$',
view=bt.view, view=bt.ViolationView.as_view(),
name="violation_url"), name="violation_url"),
url(r'^attach/(?P<id>[0-9]*)$', url(r'^attach/(?P<id>[0-9]*)$',
view=bt.get_attach, view=bt.get_attach,
...@@ -60,7 +60,7 @@ urlpatterns = patterns('', ...@@ -60,7 +60,7 @@ urlpatterns = patterns('',
view=bt.moderate, view=bt.moderate,
name="moderate"), name="moderate"),
url(r'^lookup/$', url(r'^lookup/$',
view=bt.lookup, view=bt.LookupView.as_view(),
name="lookup"), name="lookup"),
url(r'^accounts/logout$', url(r'^accounts/logout$',
'django.contrib.auth.views.logout', {'next_page': '/'}), 'django.contrib.auth.views.logout', {'next_page': '/'}),
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment