Commit 15e1f667 authored by Thom Wiggers's avatar Thom Wiggers 📐
Browse files

Merge branch 'tc/documents-class-views' into 'master'

Refactor documents views to class-based

See merge request !1258
parents 4d3c445a c0414937
"""The routes defined by the documents package""" """The routes defined by the documents package"""
from django.conf.urls import url from django.urls import path, include
from . import views from . import views
app_name = "documents" app_name = "documents"
urlpatterns = [ urlpatterns = [
url(r'^document/(?P<pk>[0-9]+)/$', views.get_document, name='document'), path('documents/', include([
url(r'^$', views.index, name='index'), path('document/<int:pk>/',
views.DocumentDownloadView.as_view(), name='document'),
path('',
views.DocumentsIndexView.as_view(), name='index'),
]))
] ]
...@@ -2,11 +2,13 @@ ...@@ -2,11 +2,13 @@
import os import os
from django.conf import settings from django.conf import settings
from django.http import Http404 from django.core.exceptions import PermissionDenied
from django.shortcuts import get_object_or_404, redirect, render from django.http import Http404, HttpResponse
from django.shortcuts import redirect
from django.utils import timezone from django.utils import timezone
from django.utils.text import slugify from django.utils.text import slugify
from django.utils.translation import get_language from django.utils.translation import get_language
from django.views.generic import TemplateView, DetailView
from sendfile import sendfile from sendfile import sendfile
from documents.models import (AnnualDocument, AssociationDocument, from documents.models import (AnnualDocument, AssociationDocument,
...@@ -14,75 +16,81 @@ from documents.models import (AnnualDocument, AssociationDocument, ...@@ -14,75 +16,81 @@ from documents.models import (AnnualDocument, AssociationDocument,
from utils.snippets import datetime_to_lectureyear from utils.snippets import datetime_to_lectureyear
def index(request): class DocumentsIndexView(TemplateView):
""" """
View that renders the documents index page View that renders the documents index page
:param request: the request object
:return: HttpResponse 200 containing the page HTML
""" """
lectureyear = datetime_to_lectureyear(timezone.now()) template_name = 'documents/index.html'
years = {x: {} for x in reversed(range(1990, lectureyear + 1))} def get_context_data(self, **kwargs) -> dict:
for year in years: lecture_year = datetime_to_lectureyear(timezone.now())
years[year] = {
'documents': { years = {x: {} for x in reversed(range(1990, lecture_year + 1))}
'policy': None, for year in years:
'report': None, years[year] = {
'financial': None 'documents': {
}, 'policy': None,
'general_meetings': [] 'report': None,
} 'financial': None
},
for document in AnnualDocument.objects.filter(subcategory='policy'): 'general_meetings': []
years[document.year]['documents']['policy'] = document }
for document in AnnualDocument.objects.filter(subcategory='report'):
years[document.year]['documents']['report'] = document for document in AnnualDocument.objects.filter(subcategory='policy'):
for document in AnnualDocument.objects.filter(subcategory='financial'): years[document.year]['documents']['policy'] = document
years[document.year]['documents']['financial'] = document for document in AnnualDocument.objects.filter(subcategory='report'):
years[document.year]['documents']['report'] = document
for obj in GeneralMeeting.objects.all(): for document in AnnualDocument.objects.filter(subcategory='financial'):
meeting_year = datetime_to_lectureyear(obj.datetime) years[document.year]['documents']['financial'] = document
years[meeting_year]['general_meetings'].append(obj)
for obj in GeneralMeeting.objects.all():
return render(request, 'documents/index.html', { meeting_year = datetime_to_lectureyear(obj.datetime)
'association_documents': years[meeting_year]['general_meetings'].append(obj)
AssociationDocument
.objects context = super().get_context_data(**kwargs)
.order_by(f'name_{ get_language() }') context.update({
.all(), 'association_documents': AssociationDocument.objects.order_by(
'years': list(years.items()) f'name_{get_language()}').all(),
}) 'years': list(years.items())
})
return context
# TODO verify if we need to check a permission instead.
# This depends on how we're dealing with ex-members.
def get_document(request, pk): class DocumentDownloadView(DetailView):
""" """
View that allows you to download a specific document based on it's and your View that allows you to download a specific document based on it's and your
permissions settings permissions settings
:param request: the request object
:param pk: primary key of the document
:return: either a 302 redirect to the login page or a 200 with the document
""" """
document = get_object_or_404(Document, pk=int(pk)) model = Document
if document.members_only and not request.user.is_authenticated: def get(self, request, *args, **kwargs) -> HttpResponse:
return redirect('{}?next={}'.format(settings.LOGIN_URL, request.path)) """
:return: either a 302 redirect to the login page or
lang = request.GET.get('language') a 200 with the document
try: """
if lang == 'nl': response = super().get(request, *args, **kwargs)
file = document.file_nl document = response.context_data['document']
elif lang == 'en':
file = document.file_en if (document.members_only and
else: # Fall back on language detection not request.user.is_authenticated):
file = document.file return redirect(
except ValueError: '{}?next={}'.format(settings.LOGIN_URL, request.path))
raise Http404('This document does not exist.') elif (document.members_only and
not request.member.has_active_membership()):
ext = os.path.splitext(file.path)[1] raise PermissionDenied
return sendfile(request, file.path, attachment=True, lang = request.GET.get('language')
attachment_filename=slugify(document.name) + ext) try:
if lang == 'nl':
file = document.file_nl
elif lang == 'en':
file = document.file_en
else: # Fall back on language detection
file = document.file
except ValueError:
raise Http404('This document does not exist.')
ext = os.path.splitext(file.path)[1]
return sendfile(request, file.path, attachment=True,
attachment_filename=slugify(document.name) + ext)
...@@ -84,7 +84,6 @@ urlpatterns = [ # pylint: disable=invalid-name ...@@ -84,7 +84,6 @@ urlpatterns = [ # pylint: disable=invalid-name
url(r'^', include([ # 'association' menu url(r'^', include([ # 'association' menu
url(r'^', include('activemembers.urls')), url(r'^', include('activemembers.urls')),
url(r'^merchandise/', include('merchandise.urls')), url(r'^merchandise/', include('merchandise.urls')),
url(r'^documents/', include('documents.urls')),
path('sibling-associations/', SiblingAssociationsView.as_view(), name='sibling-associations'), path('sibling-associations/', SiblingAssociationsView.as_view(), name='sibling-associations'),
url(r'^thabloid/', include('thabloid.urls')), url(r'^thabloid/', include('thabloid.urls')),
])), ])),
...@@ -131,5 +130,6 @@ urlpatterns = [ # pylint: disable=invalid-name ...@@ -131,5 +130,6 @@ urlpatterns = [ # pylint: disable=invalid-name
url(r'^media/private/(?P<request_path>.*)$', private_media, name='private-media'), url(r'^media/private/(?P<request_path>.*)$', private_media, name='private-media'),
url('', include('members.urls')), url('', include('members.urls')),
url('', include('payments.urls')), url('', include('payments.urls')),
url('', include('documents.urls')),
] + static(settings.MEDIA_URL + 'public/', ] + static(settings.MEDIA_URL + 'public/',
document_root=os.path.join(settings.MEDIA_ROOT, 'public')) document_root=os.path.join(settings.MEDIA_ROOT, 'public'))
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