Home Information - Your home, your data, organized.
Python
Location addition, switching, deletion and default SVG added.
Anthony Cassandra41263568c002
diff --git a/src/hi/apps/collection/collection_manager.py b/src/hi/apps/collection/collection_manager.pyindex 1b737ea8..634c31c3 100644--- a/src/hi/apps/collection/collection_manager.py+++ b/src/hi/apps/collection/collection_manager.py@@ -41,11 +41,15 @@ class CollectionManager(Singleton):collection_type : CollectionType,name : str ) -> Collection:last_collection = Collection.objects.all().order_by( '-order_id' ).first()-+ if last_collection:+ order_id = last_collection.order_id + 1+ else:+ order_id = 0+return Collection.objects.create(name = name,collection_type_str = str(collection_type),- order_id = last_collection.order_id + 1,+ order_id = order_id,)def create_collection_entity( self,@@ -53,10 +57,15 @@ class CollectionManager(Singleton):collection : Collection ) -> CollectionEntity:last_item = CollectionEntity.objects.order_by( '-order_id' ).first()+ if last_item:+ order_id = last_item.order_id + 1+ else:+ order_id = 0+return CollectionEntity.objects.create(entity = entity,collection = collection,- order_id = last_item.order_id + 1,+ order_id = order_id,)def remove_collection_entity( self,diff --git a/src/hi/apps/collection/migrations/0008_alter_collection_options.py b/src/hi/apps/collection/migrations/0008_alter_collection_options.pynew file mode 100644index 00000000..783dc2fc--- /dev/null+++ b/src/hi/apps/collection/migrations/0008_alter_collection_options.py@@ -0,0 +1,21 @@+# Generated by Django 4.2.15 on 2024-10-11 15:38++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("collection", "0007_collectionpath_and_more"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="collection",+ options={+ "ordering": ["order_id"],+ "verbose_name": "Collection",+ "verbose_name_plural": "Collections",+ },+ ),+ ]diff --git a/src/hi/apps/collection/models.py b/src/hi/apps/collection/models.pyindex c752937e..dcfe65a6 100644--- a/src/hi/apps/collection/models.py+++ b/src/hi/apps/collection/models.py@@ -36,6 +36,7 @@ class Collection( models.Model, LocationItemModelMixin ):class Meta:verbose_name = 'Collection'verbose_name_plural = 'Collections'+ ordering = [ 'order_id' ]@propertydef item_type(self) -> ItemType:diff --git a/src/hi/apps/common/models.py b/src/hi/apps/common/models.pyindex a24440c3..3b04ec5f 100644--- a/src/hi/apps/common/models.py+++ b/src/hi/apps/common/models.py@@ -4,6 +4,7 @@ from django.db import models, transactionfrom django.utils import timezone+class DatabaseLock(models.Model):name = models.CharField(@@ -60,4 +61,3 @@ class DatabaseLock(models.Model):self.initialized = Trueself.save()return-diff --git a/src/hi/apps/location/admin.py b/src/hi/apps/location/admin.pyindex 4a237730..af6c0b9c 100644--- a/src/hi/apps/location/admin.py+++ b/src/hi/apps/location/admin.py@@ -15,11 +15,8 @@ class LocationAdmin(admin.ModelAdmin):list_display = ('name',- 'svg_filename',+ 'svg_fragment_filename','svg_view_box_str',- 'latitude',- 'longitude',- 'elevation_feet','order_id','created_datetime','updated_datetime',diff --git a/src/hi/apps/location/edit/forms.py b/src/hi/apps/location/edit/forms.pyindex 5726561d..d832a74c 100644--- a/src/hi/apps/location/edit/forms.py+++ b/src/hi/apps/location/edit/forms.py@@ -1,13 +1,116 @@+import logging+import os+import time+import xml.etree.ElementTree as ET+from django import forms+from django.conf import settings+from django.core.exceptions import ValidationError++from hi.apps.common.svg_models import SvgViewBox++logger = logging.getLogger(__name__)++# Need this to avoid library adding "ns0:" namespacing when writing content.+ET.register_namespace('', 'http://www.w3.org/2000/svg')class LocationForm(forms.Form):+ LOCATION_DEFAULT_FILENAME = 'location-default.svg'+ MAX_SVG_FILE_SIZE_MEGABYTES = 5+ MAX_SVG_FILE_SIZE_BYTES = MAX_SVG_FILE_SIZE_MEGABYTES * 1024 * 1024++ DANGEROUS_TAGS = {+ 'script', 'foreignObject', 'iframe', 'object',+ 'animation', 'audio', 'video', 'style',+ }+ DANGEROUS_ATTRS = {+ 'onload', 'onclick', 'onmouseover', 'xlink:href',+ 'href',+ }+name = forms.CharField()- svg_file = forms.FileField( label = 'Select an SVG file' )+ svg_file = forms.FileField(+ label = 'SVG file',+ required = False,+ )++ def clean(self):+ cleaned_data = super().clean()++ svg_file_handle = cleaned_data.get('svg_file')+ if not svg_file_handle:+ default_svg_path = os.path.join(+ settings.BASE_DIR,+ 'static',+ 'img',+ self.LOCATION_DEFAULT_FILENAME,+ )+ with open(default_svg_path, 'r') as f:+ svg_content = f.read()+ svg_filename = self.LOCATION_DEFAULT_FILENAME+ else:+ svg_content = svg_file_handle.read().decode('utf-8')+ svg_filename = svg_file_handle.name++ try:+ if len(svg_content) > self.MAX_SVG_FILE_SIZE_BYTES:+ raise ValidationError( f'SVG file too large. Max {self.MAX_SVG_FILE_SIZE_MEGABYTES} MB.' )++ root = ET.fromstring( svg_content )+ if root.tag != '{http://www.w3.org/2000/svg}svg':+ raise ValidationError( 'The uploaded file is not a valid SVG file.' )++ view_box_str = root.attrib.get( 'viewBox' )+ if not view_box_str:+ raise ValidationError( 'The SVG must contain a viewBox attribute.' )++ svg_viewbox = SvgViewBox.from_attribute_value( view_box_str )+ cleaned_data['svg_viewbox'] = svg_viewbox++ # Remove the outer <svg> tag if necessary+ for element in list( root.iter() ):+ if element is root:+ continue++ # Remove the namespace from the child elements+ if element.tag.startswith('{http://www.w3.org/2000/svg}'):+ element.tag = element.tag.split('}', 1)[1] # Strip the namespace++ tag_name = element.tag.split('}')[-1] # Handle namespaces+ if tag_name in self.DANGEROUS_TAGS:+ logger.debug( f'Removing dangerous SVG tag "{tag_name}"' )+ root.remove(element)+ continue++ for attr in list(element.attrib):+ if attr in self.DANGEROUS_ATTRS:+ logger.debug(f'Removing dangerous SVG attribute "{attr}"')+ del element.attrib[attr]+ continue++ continue++ inner_content = ''.join( ET.tostring( element, encoding = 'unicode' ) for element in root )+ cleaned_data['svg_fragment_content'] = inner_content+ cleaned_data['svg_fragment_filename'] = self.generate_unique_filename( svg_filename )++ except ET.ParseError:+ raise ValidationError( 'The uploaded file is not a valid XML (SVG) file.' )+ except Exception as e:+ raise ValidationError(f'Error processing the SVG file: {str(e)}' )+ return cleaned_data++ def generate_unique_filename( self, filename : str ):+ original_name, extension = os.path.splitext( filename )+ timestamp = int( time.time() )+ unique_name = f'{original_name}_{timestamp}{extension}'+ return unique_name+class LocationViewForm(forms.Form):name = forms.CharField()diff --git a/src/hi/apps/location/edit/helpers.py b/src/hi/apps/location/edit/helpers.pyindex 09517f49..9fb7db80 100644--- a/src/hi/apps/location/edit/helpers.py+++ b/src/hi/apps/location/edit/helpers.py@@ -9,14 +9,12 @@ from hi.apps.collection.models import (Collection,CollectionView,)-from hi.apps.common.svg_models import SvgViewBoxfrom hi.apps.entity.delegation_manager import DelegationManagerfrom hi.apps.entity.entity_manager import EntityManagerfrom hi.apps.entity.models import (Entity,EntityView,)-from hi.apps.location.enums import LocationViewTypefrom hi.apps.location.models import Location, LocationViewfrom .transient_models import (@@ -29,57 +27,6 @@ from .transient_models import (class LocationEditHelpers:- @classmethod- def create_location( cls,- request : HttpRequest,- name : str,- svg_filename : str,- svg_view_box : SvgViewBox-- ) -> LocationView:-- location = cls.get_location_for_new_location_view( request )- if not location:- raise ValueError( 'No locations defined.' )-- last_location_view = location.views.order_by( '-order_id' ).first()-- return LocationView.objects.create(- location = location,- location_view_type_str = LocationViewType.default(),- name = name,- svg_view_box_str = str( location.svg_view_box ),- svg_rotate = Decimal( 0.0 ),- order_id = last_location_view.order_id + 1,- )-- @classmethod- def create_location_view( cls,- request : HttpRequest,- name : str ) -> LocationView:-- location = cls.get_location_for_new_location_view( request )- if not location:- raise ValueError( 'No locations defined.' )-- last_location_view = location.views.order_by( '-order_id' ).first()-- return LocationView.objects.create(- location = location,- location_view_type_str = LocationViewType.default(),- name = name,- svg_view_box_str = str( location.svg_view_box ),- svg_rotate = Decimal( 0.0 ),- order_id = last_location_view.order_id + 1,- )-- @classmethod- def get_location_for_new_location_view( cls, request : HttpRequest ) -> Location:- if request.view_parameters.location_view:- return request.view_parameters.location_view.location- return Location.objects.order_by( 'order_id' ).first()--@classmethoddef create_entity_view_group_list( cls, location_view : LocationView ) -> List[EntityViewGroup]:diff --git a/src/hi/apps/location/edit/urls.py b/src/hi/apps/location/edit/urls.pyindex 67885a02..feef6042 100644--- a/src/hi/apps/location/edit/urls.py+++ b/src/hi/apps/location/edit/urls.py@@ -9,6 +9,10 @@ urlpatterns = [views.LocationAddView.as_view(),name='location_edit_location_add'),+ re_path( r'^location/delete/(?P<location_id>\d+)$',+ views.LocationDeleteView.as_view(),+ name='location_edit_location_delete' ),+re_path( r'^location-view/add$',views.LocationViewAddView.as_view(),name='location_edit_location_view_add' ),diff --git a/src/hi/apps/location/edit/views.py b/src/hi/apps/location/edit/views.pyindex ae45909b..fd08cb85 100644--- a/src/hi/apps/location/edit/views.py+++ b/src/hi/apps/location/edit/views.py@@ -17,13 +17,18 @@ from hi.apps.entity.entity_manager import EntityManagerimport hi.apps.entity.edit.views as entity_edit_viewsfrom hi.apps.entity.models import Entityfrom hi.apps.location.forms import LocationItemPositionForm+from hi.apps.location.location_manager import LocationManagerfrom hi.apps.location.location_view_manager import LocationViewManager-from hi.apps.location.models import LocationView+from hi.apps.location.models import Location, LocationViewfrom hi.apps.location.svg_item_factory import SvgItemFactoryfrom hi.decorators import edit_requiredfrom hi.enums import ItemType, ViewTypefrom hi.hi_grid_view import HiGridView-from hi.views import bad_request_response, page_not_found_response+from hi.views import (+ bad_request_response,+ internal_error_response,+ page_not_found_response,+)from hi.constants import DIVID@@ -45,38 +50,26 @@ class LocationAddView( View ):if not location_form.is_valid():return self._show_modal( request, location_form = location_form )- svg_file = request.FILES['svg_file']try:- svg_file_path = self._handle_uploaded_svg_file( svg_file )-- except ValueError as e:- location_form.add_error( 'svg_file', str(e) )- return self._show_modal( request, location_form = location_form )-- try:- location = LocationEditHelpers.create_location(- request = request,+ location = LocationManager().create_location(name = location_form.cleaned_data.get('name'),+ svg_fragment_filename = location_form.cleaned_data.get('svg_fragment_filename'),+ svg_fragment_content = location_form.cleaned_data.get('svg_fragment_content'),+ svg_viewbox = location_form.cleaned_data.get('svg_viewbox'),)- except ValueError as e:- return bad_request_response( request, message = str(e) )------- location_view = create_all_zzz--+ except ValueError as ve:+ return bad_request_response( request, message = str(ve) )+ except Exception as e:+ logger.exception( e )+ return internal_error_response( request, message = str(e) )-+ location_view = location.views.order_by( 'order_id' ).first()request.view_parameters.view_type = ViewType.LOCATION_VIEWrequest.view_parameters.location_view_id = location_view.idrequest.view_parameters.to_session( request )redirect_url = reverse('home')- return redirect( redirect_url )+ return antinode.redirect_response( redirect_url )def _show_modal( self, request, location_form : forms.LocationForm ):context = {@@ -88,35 +81,56 @@ class LocationAddView( View ):context = context,)- def _handle_uploaded_svg_file( self, svg_file ):-- if svg_file.size > 1024 * 1024 * 5: # Example: Limit file size to 5 MB- raise ValueError("File is too large")-- for chunk in svg_file.chunks():- # Process each chunk of the file (optional)- pass-----++@method_decorator( edit_required, name='dispatch' )+class LocationDeleteView( View ):- return svg_file.name+ def get(self, request, *args, **kwargs):+ location_id = kwargs.get( 'location_id' )+ if not location_id:+ return bad_request_response( request, message = 'Missing location id.' )++ try:+ location = Location.objects.get( id = location_id )+ except Location.DoesNotExist:+ return page_not_found_response( request )+ context = {+ 'location': location,+ }+ return antinode.modal_from_template(+ request = request,+ template_name = 'location/edit/modals/location_delete.html',+ context = context,+ )+ def post( self, request, *args, **kwargs ):+ action = request.POST.get( 'action' )+ if action != 'confirm':+ return bad_request_response( request, message = 'Missing confirmation value.' )+ location_id = kwargs.get( 'location_id' )+ if not location_id:+ return bad_request_response( request, message = 'Missing location id.' )++ try:+ location = Location.objects.get( id = location_id )+ except Location.DoesNotExist:+ return page_not_found_response( request )+ location.delete()+ next_location = Location.objects.all().order_by( 'order_id' ).first()+ if next_location:+ request.view_parameters.location_id = next_location.id+ else:+ request.view_parameters.location_id = None+ request.view_parameters.to_session( request )- # Save the file to MEDIA_ROOT after processing- file_path = os.path.join( settings.MEDIA_ROOT, svg_file.name )- with default_storage.open( file_path, 'wb+' ) as destination:- for chunk in svg_file.chunks():- destination.write(chunk)- return file_path+ redirect_url = reverse('home')+ return antinode.redirect_response( redirect_url )+-@method_decorator( edit_required, name='dispatch' )class LocationViewDetailsView( View ):@@ -169,9 +183,14 @@ class LocationViewAddView( View ):context = context,)+ if request.view_parameters.location_view:+ location = request.view_parameters.location_view.location+ else:+ location = Location.objects.order_by( 'order_id' ).first()+try:- location_view = LocationEditHelpers.create_location_view(- request = request,+ location_view = LocationViewManager().create_location_view(+ location = location,name = location_view_form.cleaned_data.get('name'),)except ValueError as e:@@ -238,15 +257,13 @@ class LocationViewDeleteView( View ):def get(self, request, *args, **kwargs):location_view_id = kwargs.get( 'location_view_id' )if not location_view_id:- return bad_request_response( request, message = 'No current location view found.' )+ return bad_request_response( request, message = 'Missing location view id.' )try:location_view = LocationView.objects.select_related('location' ).get( id = location_view_id )except LocationView.DoesNotExist:- message = f'Location view "{location_view_id}" does not exist.'- logger.warning( message )- return bad_request_response( request, message = message )+ return page_not_found_response( request )context = {'location_view': location_view,@@ -270,9 +287,7 @@ class LocationViewDeleteView( View ):location_view = LocationView.objects.select_related('location' ).get( id = location_view_id )except LocationView.DoesNotExist:- message = f'Location view "{location_view_id}" does not exist.'- logger.warning( message )- return bad_request_response( request, message = message )+ return page_not_found_response( request )location_view.delete()@@ -284,7 +299,7 @@ class LocationViewDeleteView( View ):request.view_parameters.to_session( request )redirect_url = reverse('home')- return redirect( redirect_url )+ return antinode.redirect_response( redirect_url )@method_decorator( edit_required, name='dispatch' )diff --git a/src/hi/apps/location/location_manager.py b/src/hi/apps/location/location_manager.pynew file mode 100644index 00000000..43c62338--- /dev/null+++ b/src/hi/apps/location/location_manager.py@@ -0,0 +1,49 @@+from django.core.files.storage import default_storage+from django.db import transaction++from hi.apps.common.singleton import Singleton+from hi.apps.common.svg_models import SvgViewBox++from .location_view_manager import LocationViewManager+from .models import (+ Location,+ LocationView,+)+++class LocationManager(Singleton):++ INITIAL_LOCATION_VIEW_NAME = 'All'++ def __init_singleton__(self):+ return++ def create_location( self,+ name : str,+ svg_fragment_filename : str,+ svg_fragment_content : str,+ svg_viewbox : SvgViewBox ) -> LocationView:++ last_location = Location.objects.all().order_by( '-order_id' ).first()+ if last_location:+ order_id = last_location.order_id + 1+ else:+ order_id = 0++ with default_storage.open( svg_fragment_filename, 'w') as destination:+ destination.write( svg_fragment_content )++ with transaction.atomic():+ location = Location.objects.create(+ name = name,+ svg_fragment_filename= svg_fragment_filename,+ svg_view_box_str = str( svg_viewbox ),+ order_id = order_id,+ )++ _ = LocationViewManager().create_location_view(+ location = location,+ name = self.INITIAL_LOCATION_VIEW_NAME,+ )++ return locationdiff --git a/src/hi/apps/location/location_view_manager.py b/src/hi/apps/location/location_view_manager.pyindex 858c9a5a..f5b24e98 100644--- a/src/hi/apps/location/location_view_manager.py+++ b/src/hi/apps/location/location_view_manager.py@@ -1,7 +1,10 @@+from decimal import Decimal+from hi.apps.common.singleton import Singleton+from .enums import LocationViewTypefrom .location_view_data import LocationViewData-from .models import LocationView+from .models import Location, LocationViewclass LocationViewManager(Singleton):@@ -9,6 +12,25 @@ class LocationViewManager(Singleton):def __init_singleton__(self):return+ def create_location_view( self,+ location : Location,+ name : str ) -> LocationView:++ last_location_view = location.views.order_by( '-order_id' ).first()+ if last_location_view:+ order_id = last_location_view.order_id + 1+ else:+ order_id = 0++ return LocationView.objects.create(+ location = location,+ location_view_type_str = LocationViewType.default(),+ name = name,+ svg_view_box_str = str( location.svg_view_box ),+ svg_rotate = Decimal( 0.0 ),+ order_id = order_id,+ )+def get_location_view_data( self, location_view : LocationView ):location = location_view.locationdiff --git a/src/hi/apps/location/migrations/0008_alter_location_options_alter_locationview_options_and_more.py b/src/hi/apps/location/migrations/0008_alter_location_options_alter_locationview_options_and_more.pynew file mode 100644index 00000000..c5203f30--- /dev/null+++ b/src/hi/apps/location/migrations/0008_alter_location_options_alter_locationview_options_and_more.py@@ -0,0 +1,57 @@+# Generated by Django 4.2.15 on 2024-10-11 15:38++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0007_rename_view_type_str_locationview_location_view_type_str"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="location",+ options={+ "ordering": ["order_id"],+ "verbose_name": "Location",+ "verbose_name_plural": "Locations",+ },+ ),+ migrations.AlterModelOptions(+ name="locationview",+ options={+ "ordering": ["order_id"],+ "verbose_name": "View",+ "verbose_name_plural": "Views",+ },+ ),+ migrations.RemoveField(+ model_name="location",+ name="elevation_feet",+ ),+ migrations.RemoveField(+ model_name="location",+ name="latitude",+ ),+ migrations.RemoveField(+ model_name="location",+ name="longitude",+ ),+ migrations.AddField(+ model_name="location",+ name="svg_fragment_filename",+ field=models.FileField(+ default="temp",+ max_length=255,+ upload_to="",+ verbose_name="SVG Filename",+ ),+ preserve_default=False,+ ),+ migrations.AlterField(+ model_name="location",+ name="svg_filename",+ field=models.FileField(upload_to=""),+ ),+ ]diff --git a/src/hi/apps/location/migrations/0009_alter_location_svg_fragment_filename.py b/src/hi/apps/location/migrations/0009_alter_location_svg_fragment_filename.pynew file mode 100644index 00000000..0d02a721--- /dev/null+++ b/src/hi/apps/location/migrations/0009_alter_location_svg_fragment_filename.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-10-11 15:39++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0008_alter_location_options_alter_locationview_options_and_more"),+ ]++ operations = [+ migrations.AlterField(+ model_name="location",+ name="svg_fragment_filename",+ field=models.CharField(max_length=255, verbose_name="SVG Filename"),+ ),+ ]diff --git a/src/hi/apps/location/migrations/0010_alter_location_svg_view_box_str.py b/src/hi/apps/location/migrations/0010_alter_location_svg_view_box_str.pynew file mode 100644index 00000000..cf95654e--- /dev/null+++ b/src/hi/apps/location/migrations/0010_alter_location_svg_view_box_str.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-10-11 15:39++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0009_alter_location_svg_fragment_filename"),+ ]++ operations = [+ migrations.AlterField(+ model_name="location",+ name="svg_view_box_str",+ field=models.CharField(max_length=128, verbose_name="Viewbox"),+ ),+ ]diff --git a/src/hi/apps/location/migrations/0011_alter_locationview_svg_view_box_str.py b/src/hi/apps/location/migrations/0011_alter_locationview_svg_view_box_str.pynew file mode 100644index 00000000..3cb667a0--- /dev/null+++ b/src/hi/apps/location/migrations/0011_alter_locationview_svg_view_box_str.py@@ -0,0 +1,18 @@+# Generated by Django 4.2.15 on 2024-10-11 15:40++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0010_alter_location_svg_view_box_str"),+ ]++ operations = [+ migrations.AlterField(+ model_name="locationview",+ name="svg_view_box_str",+ field=models.CharField(max_length=128, verbose_name="Viewbox"),+ ),+ ]diff --git a/src/hi/apps/location/migrations/0012_remove_location_svg_filename.py b/src/hi/apps/location/migrations/0012_remove_location_svg_filename.pynew file mode 100644index 00000000..a22aa8c4--- /dev/null+++ b/src/hi/apps/location/migrations/0012_remove_location_svg_filename.py@@ -0,0 +1,17 @@+# Generated by Django 4.2.15 on 2024-10-11 15:41++from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ("location", "0011_alter_locationview_svg_view_box_str"),+ ]++ operations = [+ migrations.RemoveField(+ model_name="location",+ name="svg_filename",+ ),+ ]diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.pyindex 100ba660..b2d2091e 100644--- a/src/hi/apps/location/models.py+++ b/src/hi/apps/location/models.py@@ -1,11 +1,16 @@+import logging++from django.core.files.storage import default_storagefrom django.db import models-from hi.apps.common.svg_models import SvgIconItem, SvgPathItem, SvgViewBox+from hi.apps.common.svg_models import SvgViewBoxfrom hi.enums import ItemTypefrom hi.models import ItemTypeModelMixinfrom .enums import LocationViewType+logger = logging.getLogger(__name__)+class Location( models.Model, ItemTypeModelMixin ):@@ -14,31 +19,16 @@ class Location( models.Model, ItemTypeModelMixin ):max_length = 64,null = False, blank = False,)- svg_filename = models.CharField(- 'SVG File',- max_length = 256,+ svg_fragment_filename = models.CharField(+ 'SVG Filename',+ max_length = 255,null = False, blank = False,)svg_view_box_str = models.CharField('Viewbox',- max_length = 64,+ max_length = 128,null = False, blank = False,)- latitude = models.DecimalField(- 'Latitude',- max_digits = 11,- decimal_places = 8,- )- longitude = models.DecimalField(- 'Longitude',- max_digits = 11,- decimal_places = 8,- )- elevation_feet = models.DecimalField(- 'Elevation (ft)',- max_digits = 9,- decimal_places = 3,- )order_id = models.PositiveIntegerField('Order Id',default = 0,@@ -56,6 +46,7 @@ class Location( models.Model, ItemTypeModelMixin ):class Meta:verbose_name = 'Location'verbose_name_plural = 'Locations'+ ordering = [ 'order_id' ]def __str__(self):return f'{self.name} ({self.id})'@@ -66,7 +57,7 @@ class Location( models.Model, ItemTypeModelMixin ):@propertydef item_type(self) -> ItemType:return ItemType.LOCATION-+@propertydef svg_view_box(self):return SvgViewBox.from_attribute_value( self.svg_view_box_str )@@ -76,7 +67,27 @@ class Location( models.Model, ItemTypeModelMixin ):self.svg_view_box_str = str(svg_view_box)return+ def delete( self, *args, **kwargs ):+ """ Deleting SVG file from MEDIA_ROOT on best effort basis. Ignore if fails. """++ if self.svg_fragment_filename:+ try:+ if default_storage.exists( self.svg_fragment_filename ):+ default_storage.delete( self.svg_fragment_filename )+ logger.debug( f'Deleted SVG file: {self.svg_fragment_filename}' )+ else:+ logger.warn( f'SVG file not found: {self.svg_fragment_filename}' )+ except Exception as e:+ # Log the error or handle it accordingly+ logger.warn( f'Error deleting file {self.svg_fragment_filename}: {e}' )++ else:+ logger.warn( 'No SVG filename for model deletion.' )++ super().delete( *args, **kwargs )+ return+class LocationView( models.Model, ItemTypeModelMixin ):location = models.ForeignKey(@@ -98,7 +109,7 @@ class LocationView( models.Model, ItemTypeModelMixin ):)svg_view_box_str = models.CharField('Viewbox',- max_length = 64,+ max_length = 128,null = False, blank = False,)svg_rotate = models.DecimalField(@@ -123,6 +134,7 @@ class LocationView( models.Model, ItemTypeModelMixin ):class Meta:verbose_name = 'View'verbose_name_plural = 'Views'+ ordering = [ 'order_id' ]def __str__(self):return f'{self.name} ({self.id})'diff --git a/src/hi/apps/location/templates/location/edit/modals/location_add.html b/src/hi/apps/location/templates/location/edit/modals/location_add.htmlindex c37343f1..7fd7ff70 100644--- a/src/hi/apps/location/templates/location/edit/modals/location_add.html+++ b/src/hi/apps/location/templates/location/edit/modals/location_add.html@@ -1,7 +1,7 @@{% extends "modals/action_with_cancel.html" %}{% block preamble %}-<form action="{% url 'location_edit_location_add' %}" method="post"+<form action="{% url 'location_edit_location_add' %}" method="post" enctype="multipart/form-data"class="form" data-async="modal">{% csrf_token %}{% endblock %}diff --git a/src/hi/apps/location/templates/location/edit/modals/location_delete.html b/src/hi/apps/location/templates/location/edit/modals/location_delete.htmlnew file mode 100644index 00000000..e5e66f67--- /dev/null+++ b/src/hi/apps/location/templates/location/edit/modals/location_delete.html@@ -0,0 +1,29 @@+{% extends "modals/action_with_cancel.html" %}++{% block title_text %}+Delete Location?+{% endblock %}++{% block body %}+<div>+ Please confirm that you want to delete the location:+ <ul>+ {{ location.name }}+ </ul>+</div>+<div>+ This will also delete all views for this location. This action cannot be undone.+</div>+{% endblock %}++{% block action_right %}+<form action="{% url 'location_edit_location_delete' location_id=location.id %}"+ method="post" class="form"+ data-async="true" >+ {% csrf_token %}+ <button id="hi-delete-location-button" type="submit" class="btn btn-lg btn-danger"+ name="action" value="confirm">+ DELETE+ </button>+</form>+{% endblock %}diff --git a/src/hi/apps/location/templates/location/edit/panes/location_form.html b/src/hi/apps/location/templates/location/edit/panes/location_form.htmlindex 3c39e31c..986fa427 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_form.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_form.html@@ -18,5 +18,5 @@<div><label for="id_svg_file">Select an SVG file:</label>- <input type="file" name="svg_file" required="" id="id_svg_file">+ <input type="file" name="svg_file" id="id_svg_file"></div>diff --git a/src/hi/apps/location/templates/location/edit/panes/location_view_details.html b/src/hi/apps/location/templates/location/edit/panes/location_view_details.htmlindex f2640642..1effc77d 100644--- a/src/hi/apps/location/templates/location/edit/panes/location_view_details.html+++ b/src/hi/apps/location/templates/location/edit/panes/location_view_details.html@@ -21,3 +21,10 @@DELETE VIEW</a></div>++<div class="">+ <a href="{% url 'location_edit_location_delete' location_id=location_view_data.location_view.location.id %}"+ class="btn btn-danger btn-control" role="button" data-async="true">+ DELETE LOCATION+ </a>+</div>diff --git a/src/hi/apps/location/templates/location/location_view.html b/src/hi/apps/location/templates/location/location_view.htmlindex b50d6337..32fd3829 100644--- a/src/hi/apps/location/templates/location/location_view.html+++ b/src/hi/apps/location/templates/location/location_view.html@@ -9,7 +9,7 @@width="100%" height="100%" preserveAspectRatio="xMidYMid meet"transform="rotate({{ location_view_data.location_view.svg_rotate }} 0 0)"><g class="hi-location-view-base">- {% include_media_template location_view_data.location_view.location.svg_filename %}+ {% include_media_template location_view_data.location_view.location.svg_fragment_filename %}</g>{% for svg_path_item in location_view_data.svg_path_items %}diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.pyindex 9981bcb3..4e37292d 100644--- a/src/hi/apps/location/views.py+++ b/src/hi/apps/location/views.py@@ -17,28 +17,53 @@ logger = logging.getLogger(__name__)class LocationSwitchView( View ):- pass+ def get(self, request, *args, **kwargs):-class LocationViewDefaultView( View ):+ location_id = kwargs.get('location_id')+ try:+ location = Location.objects.get( id = location_id )+ except Location.DoesNotExist:+ return page_not_found_response( request )- def get(self, request, *args, **kwargs):+ location_view = location.views.order_by( 'order_id' ).first()+ if not location_view:+ return bad_request_response( request, message = 'No views defined for this location.' )++ request.view_parameters.view_type = ViewType.LOCATION_VIEW+ request.view_parameters.location_view_id = location_view.id+ request.view_parameters.to_session( request )- location_view = self._get_default_location_view( request )redirect_url = reverse('location_view',kwargs = { 'id': location_view.id })return HttpResponseRedirect( redirect_url )++class LocationViewDefaultView( View ):++ def get(self, request, *args, **kwargs):++ try:+ location_view = self._get_default_location_view( request )+ redirect_url = reverse(+ 'location_view',+ kwargs = { 'id': location_view.id }+ )+ except Location.DoesNotExist:+ redirect_url = reverse( 'start' )++ return HttpResponseRedirect( redirect_url )+def _get_default_location_view( self, request ):if request.view_parameters.location_view:return request.view_parameters.location_viewlocation = Location.objects.order_by( 'order_id' ).first()if not location:- return bad_request_response( request, message = 'No locations defined.' )-+ raise Location.DoesNotExist()+location_view = location.views.order_by( 'order_id' ).first()if not location_view:return bad_request_response( request, message = 'No views defined for this location.' )diff --git a/src/hi/middleware.py b/src/hi/middleware.pyindex a2ccb264..79056079 100644--- a/src/hi/middleware.py+++ b/src/hi/middleware.py@@ -53,7 +53,7 @@ class ExceptionMiddleware(object):def process_request( self, request ):return None- def process_exception(self, request, exception):+ def process_exception( self, request, exception ):ip_address = request.META.get( 'HTTP_X_FORWARDED_FOR' ) # nginx forwardedlogger.warning( f'Exception caught in middleware [{ip_address}]: {exception}' )@@ -85,6 +85,7 @@ class ExceptionMiddleware(object):if isinstance(response, HttpResponseNotAllowed):return views.method_not_allowed_response(request)if isinstance(response, HttpResponseServerError):+ logger.warning( f'Internal error in middleware' )return views.internal_error_response(request)return responsediff --git a/src/hi/static/img/location-default.svg b/src/hi/static/img/location-default.svgnew file mode 100644index 00000000..8b13078e--- /dev/null+++ b/src/hi/static/img/location-default.svg@@ -0,0 +1,22 @@+<?xml version="1.0" encoding="UTF-8" standalone="no"?>+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 20010904//EN"+ "http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd">++<svg xmlns="http://www.w3.org/2000/svg"+ width="40pc" height="40pc"+ viewBox="0 0 2000 2000">+ <path class="property-boundary"+ fill="none" stroke="black" stroke-width="1"+ d="M 64.00,81.00+ C 64.00,81.00 1905.00,78.00 1905.00,78.00+ 1905.00,78.00 1905.00,1903.00 1905.00,1903.00+ 1905.00,1903.00 64.00,1907.00 65.00,1906.00+ 66.00,1905.00 64.00,81.00 64.00,81.00 Z" />+ <path class="house-outer-wall"+ fill="none" stroke="black" stroke-width="8"+ d="M 143.00,610.00+ C 143.00,610.00 1762.00,609.00 1762.00,609.00+ 1762.00,609.00 1776.00,1609.00 1776.00,1608.00+ 1776.00,1607.00 142.00,1610.00 144.00,1610.00+ 146.00,1610.00 143.00,610.00 143.00,610.00 Z" />+</svg>diff --git a/src/hi/views.py b/src/hi/views.pyindex bc62e4ec..429294d5 100644--- a/src/hi/views.py+++ b/src/hi/views.py@@ -9,7 +9,6 @@ from django.views.generic import Viewimport hi.apps.common.antinode as antinodefrom hi.apps.common.utils import is_ajaxfrom hi.apps.location.edit.forms import LocationForm-from hi.apps.location.models import Locationdef error_response( request : HttpRequest,@@ -24,9 +23,13 @@ def error_response( request : HttpRequest,if context is None:context = {}+ if 'error_message' not in context:+ context['error_message'] = 'Error (details missing).'+ if 'message' in context:+ context['error_message'] = context['message']+if force_json or ( request.META.get('HTTP_ACCEPT', '') == 'application/json' ):- data = { 'error_message': context.get( 'message', 'Error (details missing).' ) }- return HttpResponse( json.dumps( data ),+ return HttpResponse( json.dumps( context ),content_type = "application/json",status = status_code )@@ -137,10 +140,7 @@ class HomeView( View ):def get(self, request, *args, **kwargs):- current_location = request.view_parameters.location- if not current_location:- redirect_url = reverse('start')- elif request.view_parameters.view_type.is_collection:+ if request.view_parameters.view_type.is_collection:redirect_url = reverse( 'collection_view_default' )else:redirect_url = reverse( 'location_view_default' )@@ -150,18 +150,6 @@ class HomeView( View ):class StartView( View ):def get(self, request, *args, **kwargs):---- # ZZZ TODO: REMOVE ME- if False:- if Location.objects.all().exists():- return HomeView().get( request )-----context = {'location_form': LocationForm(),}