Commit a954f234 authored by Okhin's avatar Okhin

Working on moving to class based views on issue #22

parent dccf375b
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
from django.core.files import File
from django.core.servers.basehttp import FileWrapper
from django.conf import settings
from django.conf import settings, serializers
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.core.exceptions import ObjectDoesNotExist
from django.core.mail import send_mail
......@@ -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,21 @@ 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):
return http.HttpResponse(serielizers.serialize('json', self.get_queryset())
class AddForm(FormView, MultipleObjectMixin):
template = '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 +169,86 @@ 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'] = [reports, confirms, operators]
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):
queryset = Violation.objects.filter(activationid='')
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 'all' not in self.request.GET:
queryset = queryset.exclude(state__in=['duplicate', 'closed'])
if 'country' in self.kwargs:
queryset = queryset.filter(country=self.kwargs['country'])
if 'operator' in self.kwargs:
queryset = queryset.filter(operator_ref__name=self.kwargs['operator'])
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']
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))
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
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
def get_attach(request,id):
f = get_object_or_404(Attachment, pk=id)
......@@ -270,14 +258,18 @@ 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 LookupView(SearchView, JSONMixin):
model = Violation
form_class = SearchForm
#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')
......
......@@ -14,22 +14,19 @@ 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,
url(r'^list/(?P<country>[^/]*)(/(?P<operator>[^/]*))?/$',
view=bt.ViolationsList.as_view(),
name="filter"),
url(r'^add/$',
view=bt.add,
name="add_violation"),
# 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 +57,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