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 django.views.generic import ListView, FormView, DetailView
from django.views.generic.list import MultipleObjectMixin
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.shortcuts import render_to_response, get_object_or_404, redirect
from django.template import RequestContext, loader, Context
......@@ -12,6 +14,7 @@ from django.contrib import messages
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
from django.db.models import Count
from haystack.generic_views import SearchView
from models import Violation, Attachment, Comment, Confirmation, COUNTRIES, STATUS, Operator
from tempfile import mkstemp
from datetime import datetime
......@@ -138,14 +141,26 @@ def sendverifymail(service,to,body):
return actid
def add(request):
if request.method == 'POST':
form = AddViolation(request.POST)
if form.is_valid():
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(
class JSONMixin(object):
def get(self, request, *args, **kwargs):
qs = self.get_queryset()
if qs.count():
return HttpResponse(json.dumps(sorted([(x.object.id, x.object.resource_name) for x in qs])))
else:
return HttpResponse('')
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'],
operator_ref = operator,
contract = form.cleaned_data['contract'],
......@@ -159,108 +174,96 @@ def add(request):
loophole = form.cleaned_data['loophole'],
activationid = actid
)
v.save()
#c=Confirmation(key='', email=form.cleaned_data['email'], violation=v)
#c.save()
c = Comment(
comment=form.cleaned_data['comment'],
submitter_email=form.cleaned_data['email'],
submitter_name=form.cleaned_data['nick'],
consent=form.cleaned_data['consent'],
timestamp=datetime.now(),
violation=v,
)
c.save()
for f in request.FILES.getlist('attachments[]'):
a=Attachment(comment=c, name=f.name, type=f.content_type)
m = hashlib.sha256()
for chunk in f.chunks():
m.update(chunk)
sname=m.hexdigest()
a.storage.save(sname,f)
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.'))
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))
v.save()
#c=Confirmation(key='', email=form.cleaned_data['email'], violation=v)
#c.save()
c = Comment(
comment=form.cleaned_data['comment'],
submitter_email=form.cleaned_data['email'],
submitter_name=form.cleaned_data['nick'],
consent=form.cleaned_data['consent'],
timestamp=datetime.now(),
violation=v,
)
c.save()
for f in request.FILES.getlist('attachments[]'):
a=Attachment(comment=c, name=f.name, type=f.content_type)
m = hashlib.sha256()
for chunk in f.chunks():
m.update(chunk)
sname=m.hexdigest()
a.storage.save(sname,f)
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.'))
return super(AddForm, self).form_valid(form)
# XXX obsoleted by API
#def ajax(request, country=None, operator=None):
# 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 get_queryset(self):
return Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3]
def index(request):
v_list = Violation.objects.filter(activationid='',featuredcase__isnull=False).order_by('id').reverse()[:3]
form = AddViolation()
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'))],
def get_context_data(self, **kwargs):
context = super(AddForm, self).get_context_data(**kwargs)
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'))],
reverse=True)
# countries=sorted([(i['total'],i['country'])
# for i in Violation.objects.values('country').filter(activationid='').annotate(total=Count('country'))],
# 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'))],
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)
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'))],
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'))],
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(
'index.html',
{ 'form': form,
'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))
class ViolationsList(ListView):
template_name = 'list.html'
context_object_name = 'violations'
def filter_violations(request, country, operator=None):
if not operator:
violations = Violation.objects.filter(activationid='', country=country)
if not violations.count():
violations = Violation.objects.filter(activationid='', operator_ref__name=country)
else:
violations = Violation.objects.filter(activationid='', country=country, operator_ref__name=operator)
if not request.GET.get('all'):
violations = violations.exclude(state__in=['duplicate', 'closed'])
return render_to_response('list.html',
{ "violations": violations,
"country": country,
"status": STATUS },
context_instance=RequestContext(request))
def get_queryset(self):
queryset = Violation.objects.filter(activationid='')
if 'operator' in self.kwargs:
# If i Have operator I have a country
queryset = Violation.objects.filter(activationid='',
country=self.kwargs['country'],
operator_ref__name=self.kwargs['operator'])
if 'country' in self.kwargs:
queryset = Violation.objects.filter(activationid='',
country=self.kwargs['country'])
if 'all' not in self.request.GET:
queryset = queryset.filter(activationid='').exclude(state__in=['duplicate', 'closed'])
return queryset
def list_violations(request):
violations = Violation.objects.filter(activationid='')
if not request.GET.get('all'):
violations = violations.exclude(state__in=['duplicate', 'closed'])
countries=sorted([(i['total'],i['country'])
for i in Violation.objects.values('country').filter(activationid='').exclude(state__in=['duplicate', 'closed']).annotate(total=Count('country'))],
reverse=True)
countryweights=json.dumps([{'iso2': y, 'w': x} for x, y in countries])
return render_to_response('list.html',
{"violations": violations,
"countries": dict([(y,x) for x,y in countries]),
"countryweights": countryweights,
"status": STATUS,},
#"confirms": confirms,},
context_instance=RequestContext(request))
def get_context_data(self, **kwargs):
context = super(ViolationsList, self).get_context_data(**kwargs)
if 'country' in self.kwargs:
context['country'] = self.kwargs['country']
else:
countries = sorted([(i['total'], i['country'])
for i in Violation.objects.values('country').filter(activationid='').exclude(state__in=['duplicate', 'closed']).annotate(total=Count('country'))],
reverse=True)
countryweights=json.dumps([{'iso2': y, 'w': x} for x, y in countries])
context['countries'] = countries
context['countryweights'] = countryweights
return context
def view(request,id):
v = get_object_or_404(Violation, pk=id)
if v.activationid:
raise Http404
return render_to_response('view.html', { 'v': v, },context_instance=RequestContext(request))
class ViolationView(DetailView):
model = Violation
template_name = 'view.html'
pk_url_kwarg = 'id'
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):
f = get_object_or_404(Attachment, pk=id)
......@@ -270,15 +273,6 @@ def get_attach(request,id):
response['Content-Length'] = f.storage.size
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):
response = HttpResponse(mimetype='text/csv')
response['Content-Disposition'] = 'attachment; filename=respectmynet.csv'
......
......@@ -122,5 +122,4 @@
{% endfor %}
</tbody>
</table>
</div>
{%endblock%}
......@@ -14,22 +14,22 @@ admin.autodiscover()
urlpatterns = patterns('',
url(r'^$',
view=bt.index,
view=bt.AddForm.as_view(),
name="homepage"),
url(r'^list/$',
view=bt.list_violations,
view=bt.ViolationsList.as_view(),
name="list_violations"),
url(r'^list/(?P<country>[^/]*)(/(?P<operator>[^/]*))?$',
view=bt.filter_violations,
name="filter"),
url(r'^add/$',
view=bt.add,
name="add_violation"),
url(r'^list/(?P<country>\w+)/$',
view=bt.ViolationsList.as_view(),
name="filter_country"),
url(r'^list/(?P<country>\w+)/(?P<operator>\w+)/$',
view=bt.ViolationsList.as_view(),
name="filter_operator"),
# violation cannonical url and redirections
url(r'^(?P<id>[0-9]*)$',
RedirectView.as_view(url='/view/%(id)s')),
url(r'^view/(?P<id>[0-9]*)$',
view=bt.view,
view=bt.ViolationView.as_view(),
name="violation_url"),
url(r'^attach/(?P<id>[0-9]*)$',
view=bt.get_attach,
......@@ -60,7 +60,7 @@ urlpatterns = patterns('',
view=bt.moderate,
name="moderate"),
url(r'^lookup/$',
view=bt.lookup,
view=bt.LookupView.as_view(),
name="lookup"),
url(r'^accounts/logout$',
'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