Home Information - Your home, your data, organized.
Python
Abilit to add new LocationView and Collection instances.
Anthony Cassandrad8c0f9451f15
diff --git a/src/hi/apps/collection/templates/collection/collection_buttons.html b/src/hi/apps/collection/templates/collection/collection_buttons.htmlindex 329a7073..a72238ad 100644--- a/src/hi/apps/collection/templates/collection/collection_buttons.html+++ b/src/hi/apps/collection/templates/collection/collection_buttons.html@@ -7,3 +7,12 @@</a></div>{% endfor %}+{% if request.is_editing %}+<div class="col-1">+ <a href="{% url 'edit_add_collection' %}"+ class="btn btn-success btn-control" role="button"+ data-async="modal" >+ ADD+ </a>+</div>+{% endif %}diff --git a/src/hi/apps/edit/forms.py b/src/hi/apps/edit/forms.pynew file mode 100644index 00000000..0f396ee9--- /dev/null+++ b/src/hi/apps/edit/forms.py@@ -0,0 +1,6 @@+from django import forms+++class NameForm(forms.Form):++ name = forms.CharField()diff --git a/src/hi/apps/edit/templates/edit/modals/add_collection.html b/src/hi/apps/edit/templates/edit/modals/add_collection.htmlnew file mode 100644index 00000000..5b615f77--- /dev/null+++ b/src/hi/apps/edit/templates/edit/modals/add_collection.html@@ -0,0 +1,28 @@+{% extends "modals/action_with_cancel.html" %}++{% block preamble %}+<form action="{% url 'edit_add_collection' %}" method="post"+ class="form" data-async="modal">+ {% csrf_token %}+{% endblock %}++{% block title_text %}+New Collection+{% endblock %}++{% block body %}+<div>+{% include "edit/panes/name_form.html" %}+</div>+{% endblock %}++{% block action_right %}+<button id="hi-add-collection-button" type="submit" class="btn btn-lg btn-success"+ name="action" value="add">+ ADD+</button>+{% endblock %}++{% block postamble %}+</form>+{% endblock %}diff --git a/src/hi/apps/edit/templates/edit/modals/add_location_view.html b/src/hi/apps/edit/templates/edit/modals/add_location_view.htmlnew file mode 100644index 00000000..63b8e935--- /dev/null+++ b/src/hi/apps/edit/templates/edit/modals/add_location_view.html@@ -0,0 +1,28 @@+{% extends "modals/action_with_cancel.html" %}++{% block preamble %}+<form action="{% url 'edit_add_location_view' %}" method="post"+ class="form" data-async="modal">+ {% csrf_token %}+{% endblock %}++{% block title_text %}+New Location View+{% endblock %}++{% block body %}+<div>+{% include "edit/panes/name_form.html" %}+</div>+{% endblock %}++{% block action_right %}+<button id="hi-add-location-view-button" type="submit" class="btn btn-lg btn-success"+ name="action" value="add">+ ADD+</button>+{% endblock %}++{% block postamble %}+</form>+{% endblock %}diff --git a/src/hi/apps/edit/templates/edit/panes/name_form.html b/src/hi/apps/edit/templates/edit/panes/name_form.htmlnew file mode 100644index 00000000..7e03a7ad--- /dev/null+++ b/src/hi/apps/edit/templates/edit/panes/name_form.html@@ -0,0 +1,17 @@+{% for hidden in name_form.hidden_fields %}+{{ hidden }}+{% endfor %}++{% if name_form.non_field_errors %}+<div class="non-field-errors">+ {% for err in name_form.non_field_errors %}+ <p class="form-error text-danger">ERROR: {{ err }}</p>+ {% endfor %}+</div>+{% endif %}++<div>+ {{ name_form.name.label }}+ {{ name_form.name }}+ {{ name_form.name.errors }}+</div>diff --git a/src/hi/apps/edit/urls.py b/src/hi/apps/edit/urls.pyindex c219beb1..bfba9d57 100644--- a/src/hi/apps/edit/urls.py+++ b/src/hi/apps/edit/urls.py@@ -17,6 +17,14 @@ urlpatterns = [views.EditDeleteView.as_view(),name='edit_delete' ),+ re_path( r'^location-view/add$',+ views.AddLocationViewView.as_view(),+ name='edit_add_location_view' ),++ re_path( r'^collection/add$',+ views.AddCollectionView.as_view(),+ name='edit_add_collection' ),+re_path( r'^location-view/delete$',views.DeleteLocationViewView.as_view(),name='edit_delete_location_view' ),diff --git a/src/hi/apps/edit/views.py b/src/hi/apps/edit/views.pyindex e5990d72..86924619 100644--- a/src/hi/apps/edit/views.py+++ b/src/hi/apps/edit/views.py@@ -1,3 +1,4 @@+from decimal import Decimalimport loggingimport refrom typing import Dict@@ -11,17 +12,21 @@ from django.views.generic import Viewimport hi.apps.common.antinode as antinodefrom hi.apps.collection.collection_manager import CollectionManager+from hi.apps.collection.enums import CollectionTypefrom hi.apps.collection.models import Collection, CollectionPositionfrom hi.apps.entity.models import Entity, EntityPosition+from hi.apps.location.enums import LocationViewTypefrom hi.apps.location.forms import SvgPositionFormfrom hi.apps.location.location_view_manager import LocationViewManagerfrom hi.apps.location.models import Location, LocationViewfrom hi.decorators import edit_required+from hi.enums import ViewTypefrom hi.views import bad_request_responsefrom hi.constants import DIVIDfrom hi.enums import ViewMode+from . import formsfrom .helpers_location_view import LocationViewEditHelpersfrom .helpers_collection import CollectionEditHelpers@@ -167,6 +172,112 @@ class EditDeleteView( View ):)+@method_decorator( edit_required, name='dispatch' )+class AddLocationViewView( View ):++ def get( self, request, *args, **kwargs ):+ context = {+ 'name_form': forms.NameForm(),+ }+ return antinode.modal_from_template(+ request = request,+ template_name = 'edit/modals/add_location_view.html',+ context = context,+ )++ def post( self, request, *args, **kwargs ):+ name_form = forms.NameForm( request.POST )+ if not name_form.is_valid():+ context = {+ 'name_form': name_form,+ }+ return antinode.modal_from_template(+ request = request,+ template_name = 'edit/modals/add_location_view.html',+ context = context,+ )++++ # Move to helper class+ # Extend NameForm to add type dropdown++++ location = self.get_location_for_new_location_view( request )+ if not location:+ return bad_request_response( request, message = 'No locations defined.' )++ last_location_view = location.views.order_by( '-order_id' ).first()++ location_view = LocationView.objects.create(+ location = location,+ location_view_type_str = LocationViewType.default(),+ name = name_form.cleaned_data.get('name'),+ svg_view_box_str = str( location.svg_view_box ),+ svg_rotate = Decimal( 0.0 ),+ order_id = last_location_view.order_id + 1,+ )++ request.view_parameters.view_type = ViewType.LOCATION_VIEW+ request.view_parameters.location_view_id = location_view.id+ request.view_parameters.to_session( request )++ redirect_url = reverse('home')+ return redirect( redirect_url )++ def get_location_for_new_location_view( self, request : HttpRequest ) -> Location:+ if request.view_parameters.location_view:+ return request.view_parameters.location_view.location+ return Location.objects.order_by( 'order_id' ).first()+++@method_decorator( edit_required, name='dispatch' )+class AddCollectionView( View ):++ def get( self, request, *args, **kwargs ):+ context = {+ 'name_form': forms.NameForm(),+ }+ return antinode.modal_from_template(+ request = request,+ template_name = 'edit/modals/add_collection.html',+ context = context,+ )++ def post( self, request, *args, **kwargs ):+ name_form = forms.NameForm( request.POST )+ if not name_form.is_valid():+ context = {+ 'name_form': name_form,+ }+ return antinode.modal_from_template(+ request = request,+ template_name = 'edit/modals/add_location_view.html',+ context = context,+ )++ # Move to helper class+ # Extend NameForm to add type dropdown++++ last_collection = Collection.objects.all().order_by( '-order_id' ).first()++ collection = Collection.objects.create(+ name = name_form.cleaned_data.get('name'),+ collection_type_str = CollectionType.default(),+ order_id = last_collection.order_id + 1,+ )++ request.view_parameters.view_type = ViewType.COLLECTION+ request.view_parameters.collection_id = collection.id+ request.view_parameters.to_session( request )++ redirect_url = reverse('home')+ return redirect( redirect_url )++@method_decorator( edit_required, name='dispatch' )class DeleteLocationViewView( View ):diff --git a/src/hi/apps/location/templates/location/location_view_buttons.html b/src/hi/apps/location/templates/location/location_view_buttons.htmlindex f824a573..cbdf3366 100644--- a/src/hi/apps/location/templates/location/location_view_buttons.html+++ b/src/hi/apps/location/templates/location/location_view_buttons.html@@ -7,3 +7,12 @@</a></div>{% endfor %}+{% if request.is_editing %}+<div class="col-1">+ <a href="{% url 'edit_add_location_view' %}"+ class="btn btn-success btn-control" role="button"+ data-async="modal" >+ ADD+ </a>+</div>+{% endif %}diff --git a/src/hi/middleware.py b/src/hi/middleware.pyindex ea3c3ebe..a2ccb264 100644--- a/src/hi/middleware.py+++ b/src/hi/middleware.py@@ -1,7 +1,22 @@-from constance import configimport logging+from django.conf import settings+from django.core.exceptions import (+ BadRequest,+ PermissionDenied,+ SuspiciousOperation,+)+from django.http import (+ Http404,+ HttpResponseBadRequest,+ HttpResponseForbidden,+ HttpResponseNotFound,+ HttpResponseNotAllowed,+ HttpResponseServerError,+)+from .view_parameters import ViewParameters+from . import viewslogger = logging.getLogger(__name__)@@ -20,4 +35,57 @@ class ViewMiddleware:request.view_parameters = ViewParameters.from_session( request )request.is_editing = request.view_parameters.view_mode.is_editingreturn++class ExceptionMiddleware(object):++ def __init__(self, get_response):+ self.get_response = get_response+ return++ def __call__(self, request):+ response = self.process_request( request )+ if response:+ return response+ response = self.get_response(request)+ return self.process_response( request, response )++ def process_request( self, request ):+ return None++ def process_exception(self, request, exception):+ ip_address = request.META.get( 'HTTP_X_FORWARDED_FOR' ) # nginx forwarded+ logger.warning( f'Exception caught in middleware [{ip_address}]: {exception}' )++ if isinstance( exception, BadRequest ):+ return views.bad_request_response(request, message=str(exception))+ if isinstance( exception, SuspiciousOperation ):+ return views.bad_request_response(request, message=str(exception))+ if isinstance( exception, PermissionDenied ):+ return views.not_authorized_response(request, message=str(exception))+ if isinstance( exception, Http404 ):+ return views.page_not_found_response(request, message=str(exception))++ logger.exception( f'Exception caught in middleware: {exception}' )+ return views.internal_error_response(request, message=str(exception) )++ def process_response(self, request, response):++ if isinstance(response, HttpResponseBadRequest):+ return views.bad_request_response(request)+ if isinstance(response, HttpResponseForbidden):+ return views.not_authorized_response(request)+ if isinstance(response, HttpResponseNotFound):+ # We define a custom 404 handler (in urls.py) and emit this+ # response type, so no need to double up. However, the custom+ # 404 handler is not used when DEBUG=True.+ if settings.DEBUG:+ return views.page_not_found_response(request)+ return response+ if isinstance(response, HttpResponseNotAllowed):+ return views.method_not_allowed_response(request)+ if isinstance(response, HttpResponseServerError):+ return views.internal_error_response(request)+ return response++diff --git a/src/hi/settings/base.py b/src/hi/settings/base.pyindex dad6999c..d664b5e8 100644--- a/src/hi/settings/base.py+++ b/src/hi/settings/base.py@@ -158,6 +158,8 @@ MIDDLEWARE = ['django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware',++ 'hi.middleware.ExceptionMiddleware','hi.middleware.ViewMiddleware',]diff --git a/src/hi/templates/modals/internal_error.html b/src/hi/templates/modals/internal_error.htmlnew file mode 100644index 00000000..02a877e9--- /dev/null+++ b/src/hi/templates/modals/internal_error.html@@ -0,0 +1,5 @@+{% extends "modals/error_base.html" %}++{% block title_text %}+Internal Error+{% endblock %}diff --git a/src/hi/templates/modals/method_not_allowed.html b/src/hi/templates/modals/method_not_allowed.htmlnew file mode 100644index 00000000..edf4f98a--- /dev/null+++ b/src/hi/templates/modals/method_not_allowed.html@@ -0,0 +1,5 @@+{% extends "modals/error_base.html" %}++{% block title_text %}+Method Not Allowed+{% endblock %}diff --git a/src/hi/templates/modals/not_authorized.html b/src/hi/templates/modals/not_authorized.htmlnew file mode 100644index 00000000..f1f24a59--- /dev/null+++ b/src/hi/templates/modals/not_authorized.html@@ -0,0 +1,5 @@+{% extends "modals/error_base.html" %}++{% block title_text %}+Not Authorized+{% endblock %}diff --git a/src/hi/templates/modals/page_not_found.html b/src/hi/templates/modals/page_not_found.htmlnew file mode 100644index 00000000..893ec2fe--- /dev/null+++ b/src/hi/templates/modals/page_not_found.html@@ -0,0 +1,5 @@+{% extends "modals/error_base.html" %}++{% block title_text %}+Page Not Found+{% endblock %}diff --git a/src/hi/templates/modals/transient_error.html b/src/hi/templates/modals/transient_error.htmlnew file mode 100644index 00000000..f004a268--- /dev/null+++ b/src/hi/templates/modals/transient_error.html@@ -0,0 +1,5 @@+{% extends "modals/error_base.html" %}++{% block title_text %}+Transient Error+{% endblock %}diff --git a/src/hi/urls.py b/src/hi/urls.pyindex 17441e30..63908fb7 100644--- a/src/hi/urls.py+++ b/src/hi/urls.py@@ -32,7 +32,18 @@ urlpatterns = [re_path( r'^integration/', include('hi.integrations.core.urls' )),re_path( r'^location/', include('hi.apps.location.urls' )),re_path( r'^collection/', include('hi.apps.collection.urls' )),-++ # Custom error pages+ re_path( r'^400.html$', views.bad_request_response, name='bad_request' ),+ re_path( r'^403.html$', views.not_authorized_response, name='not_authorized' ),+ re_path( r'^404.html$', views.page_not_found_response, name='page_not_found' ),+ re_path( r'^405.html$', views.method_not_allowed_response, name='method_not_allowed' ),+ re_path( r'^500.html$', views.internal_error_response, name='internal_error' ),+ re_path( r'^503.html$', views.transient_error_response, name='transient_error' ),+]urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)++handler404 = 'hi.views.custom_404_handler'+diff --git a/src/hi/views.py b/src/hi/views.pyindex 1b519c8b..6971dbe5 100644--- a/src/hi/views.py+++ b/src/hi/views.py@@ -1,7 +1,7 @@import jsonfrom typing import Dict-from django.http import HttpRequest, HttpResponse, HttpResponseRedirect+from django.http import HttpRequest, HttpResponse, HttpResponseRedirect, HttpResponseNotFoundfrom django.shortcuts import renderfrom django.urls import reversefrom django.views.generic import View@@ -46,11 +46,75 @@ def bad_request_response( request, message : str = None, force_json : bool = Falreturn error_response( request = request,sync_template_name = "pages/bad_request.html",async_template_name = "modals/bad_request.html",- status_code = 200, # Needed for PWA (not 403)+ status_code = 400,+ force_json = force_json,+ context = context )+++def not_authorized_response( request, message : str = None, force_json : bool = False ):+ if not message:+ message = 'Not authorized.'+ context = { 'message': message }+ return error_response( request = request,+ sync_template_name = "pages/not_authorized.html",+ async_template_name = "modals/not_authorized.html",+ status_code = 403,+ force_json = force_json,+ context = context )+++def method_not_allowed_response( request, message : str = None, force_json : bool = False ):+ if not message:+ message = 'Method not allowed.'+ context = { 'message': message }+ return error_response( request = request,+ sync_template_name = "pages/method_not_allowed.html",+ async_template_name = "modals/method_not_allowed.html",+ status_code = 405,+ force_json = force_json,+ context = context )+++def page_not_found_response( request, message : str = None, force_json : bool = False ):+ if not message:+ message = 'Page not found.'+ context = { 'message': message }+ return error_response( request = request,+ sync_template_name = "pages/page_not_found.html",+ async_template_name = "modals/page_not_found.html",+ status_code = 404,+ force_json = force_json,+ context = context )+++def internal_error_response( request, message : str = None, force_json : bool = False ):+ if not message:+ message = 'Internal error.'+ context = { 'message': message }+ return error_response( request = request,+ sync_template_name = "pages/internal_error.html",+ async_template_name = "modals/internal_error.html",+ status_code = 500,force_json = force_json,context = context )+def transient_error_response( request, message : str = None, force_json : bool = False ):+ if not message:+ message = 'Transient error.'+ context = { 'message': message }+ return error_response( request = request,+ sync_template_name = "pages/transient_error.html",+ async_template_name = "modals/transient_error.html",+ status_code = 503,+ force_json = force_json,+ context = context )+++def custom_404_handler( request, exception):+ return HttpResponseNotFound( page_not_found_response( request ))++def edit_required_response( request, message : str = None, force_json : bool = False ):if not message:message = 'Edit mode is required for this request.'