Skip to content

Home Information - Your home, your data, organized.

Python

More progress on Attribute editing. WIP

Anthony Cassandra263a98e46499
diff --git a/src/hi/apps/attribute/enums.py b/src/hi/apps/attribute/enums.py
index 43e39cec..383660e3 100644
--- a/src/hi/apps/attribute/enums.py
+++ b/src/hi/apps/attribute/enums.py
@@ -18,23 +18,8 @@ class AttributeValueType(LabeledEnum):
return
TEXT = ('Text', '' )
- STRING = ('String', '' )
- PDF = ('PDF', '', True ) # relative filename of MEDIA_ROOT
- IMAGE = ('Image', '', True ) # relative filename of MEDIA_ROOT
- VIDEO = ('Video', '', True ) # relative filename of MEDIA_ROOT
- AUDIO = ('Audio', '', True ) # relative filename of MEDIA_ROOT
FILE = ('File', '', True ) # relative filename of MEDIA_ROOT
- DATETIME = ('DateTime', '' )
- DATE = ('Date', '' )
- LINK = ('Link', '' )
- PASSWORD = ('Password', '' )
- EMAIL = ('Email', '' )
- PHONE = ('Phone', '' )
- INTEGER = ('Integer', '' )
- FLOAT = ('Float', '' )
- BOOLEAN = ('Boolean', '' )
- TIME = ('Time', '' )
- JSON = ('JSON', '' )
+ SECRET = ('Secret', '' )
@classmethod
def default(cls):
diff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.py
index 0c5ed9a5..6bfc98cd 100644
--- a/src/hi/apps/attribute/forms.py
+++ b/src/hi/apps/attribute/forms.py
@@ -1,10 +1,5 @@
-import json
-
-from django.core.validators import validate_email, URLValidator
-from django.core.exceptions import ValidationError
from django.core.files.storage import default_storage
from django import forms
-from django.utils.dateparse import parse_date, parse_datetime, parse_time
from .enums import AttributeValueType
@@ -33,47 +28,14 @@ class AttributeForm(forms.ModelForm):
if instance and instance.value_type:
value_type = instance.value_type
- if value_type == AttributeValueType.INTEGER:
- self.fields['value'].widget = forms.NumberInput(
- attrs={'class': 'form-control'},
- )
- elif value_type == AttributeValueType.FLOAT:
- self.fields['value'].widget = forms.NumberInput(
- attrs={'step': 'any', 'class': 'form-control'},
- )
- elif value_type == AttributeValueType.BOOLEAN:
- self.fields['value'].widget = forms.CheckboxInput(
- )
- elif value_type == AttributeValueType.DATE:
- self.fields['value'].widget = forms.DateInput(
- attrs={'type': 'date', 'class': 'form-control'},
- )
- elif value_type == AttributeValueType.DATETIME:
- self.fields['value'].widget = forms.DateTimeInput(
- attrs={'type': 'datetime-local', 'class': 'form-control'},
- )
- elif value_type == AttributeValueType.TIME:
- self.fields['value'].widget = forms.TimeInput(
- attrs={'type': 'time', 'class': 'form-control'},
- )
- elif value_type == AttributeValueType.TEXT:
- self.fields['value'].widget = forms.Textarea(
- attrs={'class': 'form-control'},
- )
- elif value_type == AttributeValueType.EMAIL:
- self.fields['value'].widget = forms.EmailInput(
- attrs={'class': 'form-control'},
- )
- elif value_type == AttributeValueType.LINK:
- self.fields['value'].widget = forms.URLInput(
+ if value_type == AttributeValueType.FILE:
+ # File input for media types
+ self.fields['value'].widget = forms.FileInput(
attrs={'class': 'form-control'},
)
- elif value_type in { AttributeValueType.IMAGE,
- AttributeValueType.PDF,
- AttributeValueType.VIDEO,
- AttributeValueType.AUDIO }:
+ elif value_type == AttributeValueType.SECRET:
# File input for media types
- self.fields['value'].widget = forms.FileInput(
+ self.fields['value'].widget = forms.PasswordInput(
attrs={'class': 'form-control'},
)
else:
@@ -99,67 +61,11 @@ class AttributeForm(forms.ModelForm):
value = cleaned_data.get('value')
value_type = self.instance.value_type
- # Validate based on value_type
- if value_type == AttributeValueType.INTEGER:
- try:
- int(value)
- except ValueError:
- self.add_error('value', 'Value must be an integer.')
-
- elif value_type == AttributeValueType.FLOAT:
- try:
- float(value)
- except ValueError:
- self.add_error('value', 'Value must be numeric.')
-
- elif value_type in { AttributeValueType.STRING,
- AttributeValueType.TEXT }:
+ if value_type in { AttributeValueType.TEXT }:
if not isinstance(value, str):
self.add_error('value', 'Value must be a string.')
- elif value_type == AttributeValueType.EMAIL:
- try:
- validate_email(value)
- except ValidationError:
- self.add_error('value', 'Not a valid email address.')
-
- elif value_type == AttributeValueType.LINK:
- try:
- URLValidator(value)
- except ValidationError:
- self.add_error('value', 'Not a valid URL.')
-
- elif value_type == AttributeValueType.PHONE:
- # Simple phone number validation (customize if needed)
- if not value.isdigit() or len(value) < 10:
- self.add_error('value', 'Not a valid phone number.')
-
- elif value_type == AttributeValueType.BOOLEAN:
- if value not in [True, False, 'True', 'False', 1, 0]:
- self.add_error('value', 'Value must be a boolean.')
-
- elif value_type == AttributeValueType.DATETIME:
- if not parse_datetime(value):
- self.add_error('value', 'Value must be a valid datetime.')
-
- elif value_type == AttributeValueType.DATE:
- if not parse_date(value):
- self.add_error('value', 'Value must be a valid date.')
-
- elif value_type == AttributeValueType.TIME:
- if not parse_time(value):
- self.add_error('value', 'Value must be a valid time.')
-
- elif value_type == AttributeValueType.JSON:
- try:
- json.loads(value)
- except ValueError:
- self.add_error('value', 'Value must be a valid JSON.')
-
- elif value_type in { AttributeValueType.PDF,
- AttributeValueType.IMAGE,
- AttributeValueType.VIDEO,
- AttributeValueType.AUDIO }:
+ elif value_type in { AttributeValueType.FILE }:
if not default_storage.exists( value ):
self.add_error('value', f'{value_type} file does not exist.')
diff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.py
index ef5de469..aec0779f 100644
--- a/src/hi/apps/attribute/models.py
+++ b/src/hi/apps/attribute/models.py
@@ -1,5 +1,7 @@
from django.db import models
+from hi.apps.common.file_utils import generate_unique_filename
+
from hi.integrations.core.integration_key import IntegrationKey
from .enums import (
@@ -21,7 +23,7 @@ class AttributeModel(models.Model):
'Value',
)
file_value = models.FileField(
- upload_to = 'uploads/attributes/',
+ upload_to = 'attributes/', # Subclasses override via get_upload_to()
blank = True, null = True,
)
value_type_str = models.CharField(
@@ -95,3 +97,13 @@ class AttributeModel(models.Model):
self.attribute_type_str = str(attribute_type)
return
+ def get_upload_to(self):
+ raise NotImplementedError('Subclasses should override this method.' )
+
+ def save(self, *args, **kwargs):
+ if self.file_value and self.file_value.name:
+ self.file_value.field.upload_to = self.get_upload_to()
+ self.file_value.name = generate_unique_filename( self.file_value.name )
+ super().save(*args, **kwargs)
+ return
+
diff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html
index 65af086c..010d2c79 100644
--- a/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html
+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form.html
@@ -12,7 +12,6 @@
</div>
{% endif %}
- Instance = {{ attribute_form.instance.pk }}
{% if attribute_form.instance.pk %}
<div class="hi-attribute-existing">
{% if attribute_form.instance.is_editable %}
diff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_existing.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_existing.html
index 994ac773..533f6e73 100644
--- a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_existing.html
+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_existing.html
@@ -21,3 +21,6 @@ EXISTING
{{ attribute_form.value_type_str }}
{{ attribute_form.value_type_str.errors }}
</div>
+<div class="col-lg-2 col-12">
+ {{ attribute_form.DELETE }} Delete
+</div>
diff --git a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_new.html b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_new.html
index ba0c00fd..a9b91eba 100644
--- a/src/hi/apps/attribute/templates/attribute/panes/attribute_form_new.html
+++ b/src/hi/apps/attribute/templates/attribute/panes/attribute_form_new.html
@@ -1,3 +1,4 @@
+ADD
<div class="row p-3">
<div class="col-8">
<div class="input-group" >
diff --git a/src/hi/apps/common/file_utils.py b/src/hi/apps/common/file_utils.py
new file mode 100644
index 00000000..5ac289b0
--- /dev/null
+++ b/src/hi/apps/common/file_utils.py
@@ -0,0 +1,9 @@
+import os
+import time
+
+
+def generate_unique_filename( filename : str ):
+ original_name, extension = os.path.splitext( filename )
+ timestamp = int( time.time() )
+ unique_name = f'{original_name}-{timestamp}{extension}'
+ return unique_name
diff --git a/src/hi/apps/common/svg_forms.py b/src/hi/apps/common/svg_forms.py
index af591ccb..fc0ae63d 100644
--- a/src/hi/apps/common/svg_forms.py
+++ b/src/hi/apps/common/svg_forms.py
@@ -6,6 +6,7 @@ import xml.etree.ElementTree as ET
from django import forms
from django.core.exceptions import ValidationError
+from hi.apps.common.file_utils import generate_unique_filename
from hi.apps.common.svg_models import SvgViewBox
logger = logging.getLogger(__name__)
@@ -176,7 +177,7 @@ class SvgFileForm(forms.Form):
svg_fragment_filename = os.path.join(
self.get_media_destination_directory(),
- self.generate_unique_filename( svg_filename ),
+ generate_unique_filename( svg_filename ),
)
cleaned_data['svg_fragment_filename'] = svg_fragment_filename
@@ -217,9 +218,3 @@ class SvgFileForm(forms.Form):
self.add_error( 'svg_file', f'- Attr: {attr_name}, Count: {count:,} ' )
continue
return
-
- 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
diff --git a/src/hi/apps/entity/edit/async_views.py b/src/hi/apps/entity/edit/async_views.py
index 84810a1d..405cdac2 100644
--- a/src/hi/apps/entity/edit/async_views.py
+++ b/src/hi/apps/entity/edit/async_views.py
@@ -26,15 +26,21 @@ class EntityEditView( View, EntityViewMixin ):
entity = self.get_entity( request, *args, **kwargs )
entity_form = forms.EntityForm( request.POST, instance = entity )
- entity_attribute_formset = forms.EntityAttributeFormset(
+ entity_attribute_formset = forms.EntityAttributeFormSet(
request.POST,
request.FILES,
instance = entity,
+ prefix = f'entity-{entity.id}',
)
if entity_form.is_valid() and entity_attribute_formset.is_valid():
with transaction.atomic():
entity_form.save()
entity_attribute_formset.save()
+ # Recreate to preserve "max" to show new form
+ entity_attribute_formset = forms.EntityAttributeFormSet(
+ instance = entity,
+ prefix = f'entity-{entity.id}',
+ )
context = {
'entity': entity,
diff --git a/src/hi/apps/entity/edit/forms.py b/src/hi/apps/entity/edit/forms.py
index b8d9d973..f3c1081e 100644
--- a/src/hi/apps/entity/edit/forms.py
+++ b/src/hi/apps/entity/edit/forms.py
@@ -29,7 +29,7 @@ class EntityAttributeForm( GeneralAttributeForm ):
model = EntityAttribute
-EntityAttributeFormset = forms.inlineformset_factory(
+EntityAttributeFormSet = forms.inlineformset_factory(
Entity,
EntityAttribute,
form = EntityAttributeForm,
diff --git a/src/hi/apps/entity/entity_detail_data.py b/src/hi/apps/entity/entity_detail_data.py
index 6687cc4f..488a073a 100644
--- a/src/hi/apps/entity/entity_detail_data.py
+++ b/src/hi/apps/entity/entity_detail_data.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass
-from hi.apps.entity.edit.forms import EntityAttributeFormset, EntityForm, EntityPositionForm
+from hi.apps.entity.edit.forms import EntityAttributeFormSet, EntityForm, EntityPositionForm
from .models import Entity
@@ -10,6 +10,6 @@ class EntityDetailData:
entity : Entity
entity_form : EntityForm
- entity_attribute_formset : EntityAttributeFormset
+ entity_attribute_formset : EntityAttributeFormSet
entity_position_form : EntityPositionForm
diff --git a/src/hi/apps/entity/entity_manager.py b/src/hi/apps/entity/entity_manager.py
index 91d6332e..c185d1cd 100644
--- a/src/hi/apps/entity/entity_manager.py
+++ b/src/hi/apps/entity/entity_manager.py
@@ -4,7 +4,7 @@ from typing import List
from django.db import transaction
from hi.apps.common.singleton import Singleton
-from hi.apps.entity.edit.forms import EntityAttributeFormset, EntityForm, EntityPositionForm
+from hi.apps.entity.edit.forms import EntityAttributeFormSet, EntityForm, EntityPositionForm
from hi.apps.location.models import Location, LocationView
from hi.apps.location.svg_item_factory import SvgItemFactory
@@ -229,8 +229,9 @@ class EntityManager(Singleton):
return EntityDetailData(
entity = entity,
entity_form = EntityForm( instance = entity ),
- entity_attribute_formset = EntityAttributeFormset(
+ entity_attribute_formset = EntityAttributeFormSet(
instance = entity,
+ prefix = f'entity-{entity.id}',
form_kwargs = {
'show_as_editable': True,
},
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 1905ed63..9453ca3e 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -102,7 +102,10 @@ class EntityAttribute( AttributeModel ):
indexes = [
models.Index( fields=[ 'name', 'value' ] ),
]
-
+
+ def get_upload_to(self):
+ return 'entity/attributes/'
+
class EntityState( models.Model ):
"""
diff --git a/src/hi/apps/location/async_views.py b/src/hi/apps/location/async_views.py
index cac7bf71..b5defa6d 100644
--- a/src/hi/apps/location/async_views.py
+++ b/src/hi/apps/location/async_views.py
@@ -8,7 +8,7 @@ from django.views.generic import View
from hi.apps.collection.async_views import CollectionDetailsView
from hi.apps.entity.async_views import EntityDetailsView
from hi.apps.location.edit.forms import (
- LocationAttributeFormset,
+ LocationAttributeFormSet,
LocationEditForm,
LocationViewEditForm,
)
@@ -35,8 +35,9 @@ class LocationViewDetailsView( HiSideView, LocationViewMixin ):
return {
'location': location_view.location,
'location_edit_form': LocationEditForm( instance = location_view.location ),
- 'location_attribute_formset': LocationAttributeFormset(
+ 'location_attribute_formset': LocationAttributeFormSet(
instance = location_view.location,
+ prefix = f'location-{location_view.location.id}',
form_kwargs = {
'show_as_editable': True,
},
diff --git a/src/hi/apps/location/edit/async_views.py b/src/hi/apps/location/edit/async_views.py
index 4e50ca5b..552055ed 100644
--- a/src/hi/apps/location/edit/async_views.py
+++ b/src/hi/apps/location/edit/async_views.py
@@ -38,9 +38,11 @@ class LocationEditView( View, LocationViewMixin ):
request.POST,
instance = location,
)
- location_attribute_formset = forms.LocationAttributeFormset(
+ location_attribute_formset = forms.LocationAttributeFormSet(
request.POST,
+ request.FILES,
instance = location,
+ prefix = f'location-{location.id}',
)
context = {
@@ -51,6 +53,11 @@ class LocationEditView( View, LocationViewMixin ):
if ( not location_edit_form.is_valid()
or not location_attribute_formset.is_valid() ):
+ # Recreate to preserve "max" to show new form
+ location_attribute_formset = forms.LocationAttributeFormSet(
+ instance = location,
+ prefix = f'location-{location.id}',
+ )
template = get_template( 'location/edit/panes/location_edit.html' )
content = template.render( context, request = request )
return antinode.response(
diff --git a/src/hi/apps/location/edit/forms.py b/src/hi/apps/location/edit/forms.py
index 560b4494..335b31de 100644
--- a/src/hi/apps/location/edit/forms.py
+++ b/src/hi/apps/location/edit/forms.py
@@ -71,7 +71,7 @@ class LocationAttributeForm( GeneralAttributeForm ):
model = LocationAttribute
-LocationAttributeFormset = forms.inlineformset_factory(
+LocationAttributeFormSet = forms.inlineformset_factory(
Location,
LocationAttribute,
form = LocationAttributeForm,
diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.py
index d07a6ba1..2cbee765 100644
--- a/src/hi/apps/location/models.py
+++ b/src/hi/apps/location/models.py
@@ -108,6 +108,9 @@ class LocationAttribute( AttributeModel ):
indexes = [
models.Index( fields=[ 'name', 'value' ] ),
]
+
+ def get_upload_to(self):
+ return 'location/attributes/'
class LocationView( models.Model, ItemTypeModelMixin ):
diff --git a/src/hi/integrations/core/models.py b/src/hi/integrations/core/models.py
index 2c2e4757..1b88a017 100644
--- a/src/hi/integrations/core/models.py
+++ b/src/hi/integrations/core/models.py
@@ -59,6 +59,9 @@ class IntegrationAttribute( AttributeModel ):
verbose_name = 'Attribute'
verbose_name_plural = 'Attributes'
+ def get_upload_to(self):
+ return 'integration/attributes/'
+
class IntegrationKeyModel( models.Model ):
"""
diff --git a/src/hi/integrations/hass/enums.py b/src/hi/integrations/hass/enums.py
index 066e6462..a4c0882f 100644
--- a/src/hi/integrations/hass/enums.py
+++ b/src/hi/integrations/hass/enums.py
@@ -7,14 +7,14 @@ class HassAttributeType( IntegrationAttributeType ):
API_BASE_URL = (
'Server URL',
'e.g., https://myhassserver:8123',
- AttributeValueType.STRING,
+ AttributeValueType.TEXT,
True,
True,
)
API_TOKEN = (
'API Token',
'',
- AttributeValueType.STRING,
+ AttributeValueType.TEXT,
True,
True,
)
diff --git a/src/hi/integrations/hass/hass_converter.py b/src/hi/integrations/hass/hass_converter.py
index 5493f6fd..f0e6c4c0 100644
--- a/src/hi/integrations/hass/hass_converter.py
+++ b/src/hi/integrations/hass/hass_converter.py
@@ -238,7 +238,7 @@ class HassConverter:
entity = entity,
name = AttributeName.INSTEON_ADDRESS,
value = insteon_address,
- value_type_str = str( AttributeValueType.STRING ),
+ value_type_str = str( AttributeValueType.TEXT ),
attribute_type_str = str( AttributeType.PREDEFINED ),
is_editable = False,
is_required = False,
diff --git a/src/hi/integrations/hass/views.py b/src/hi/integrations/hass/views.py
index bb317767..f100895f 100644
--- a/src/hi/integrations/hass/views.py
+++ b/src/hi/integrations/hass/views.py
@@ -28,6 +28,7 @@ class HassEnableView( View, IntegrationHelperMixin ):
integration_attribute_formset = IntegrationAttributeFormSet(
instance = integration,
+ prefix = f'integration-{integration.id}',
form_kwargs = {
'show_as_editable': True,
},
@@ -49,6 +50,7 @@ class HassEnableView( View, IntegrationHelperMixin ):
request.POST,
request.FILES,
instance = integration,
+ prefix = f'integration-{integration.id}',
)
if not integration_attribute_formset.is_valid():
return self.get_modal_response(
@@ -100,6 +102,7 @@ class HassManageView( View, IntegrationHelperMixin ):
integration_attribute_formset = IntegrationAttributeFormSet(
instance = integration,
+ prefix = f'integration-{integration.id}',
form_kwargs = {
'show_as_editable': True,
},
@@ -125,6 +128,7 @@ class HassSettingsView( View, IntegrationHelperMixin ):
request.POST,
request.FILES,
instance = integration,
+ prefix = f'integration-{integration.id}',
)
if not integration_attribute_formset.is_valid():
context = {
diff --git a/src/hi/integrations/zoneminder/enums.py b/src/hi/integrations/zoneminder/enums.py
index a1ce1c1a..12880ce7 100644
--- a/src/hi/integrations/zoneminder/enums.py
+++ b/src/hi/integrations/zoneminder/enums.py
@@ -9,28 +9,28 @@ class ZmAttributeType( IntegrationAttributeType ):
API_URL = (
'API URL',
'e.g., https://myserver:8443/zm/api',
- AttributeValueType.LINK,
+ AttributeValueType.TEXT,
True,
True,
)
PORTAL_URL = (
'Portal URL',
'e.g., https://myserver:8443/zm',
- AttributeValueType.LINK,
+ AttributeValueType.TEXT,
True,
True,
)
API_USER = (
'Username',
'',
- AttributeValueType.STRING,
+ AttributeValueType.TEXT,
True,
True,
)
API_PASSWORD = (
'Password',
'',
- AttributeValueType.PASSWORD,
+ AttributeValueType.SECRET,
True,
True,
)
diff --git a/src/hi/integrations/zoneminder/views.py b/src/hi/integrations/zoneminder/views.py
index 9bc56651..1c66cc08 100644
--- a/src/hi/integrations/zoneminder/views.py
+++ b/src/hi/integrations/zoneminder/views.py
@@ -28,6 +28,7 @@ class ZmEnableView( View, IntegrationHelperMixin ):
integration_attribute_formset = IntegrationAttributeFormSet(
instance = integration,
+ prefix = f'integration-{integration.id}',
form_kwargs = {
'show_as_editable': True,
},
@@ -49,6 +50,7 @@ class ZmEnableView( View, IntegrationHelperMixin ):
request.POST,
request.FILES,
instance = integration,
+ prefix = f'integration-{integration.id}',
)
if not integration_attribute_formset.is_valid():
return self.get_modal_response(
@@ -100,6 +102,7 @@ class ZmManageView( View, IntegrationHelperMixin ):
integration_attribute_formset = IntegrationAttributeFormSet(
instance = integration,
+ prefix = f'integration-{integration.id}',
form_kwargs = {
'show_as_editable': True,
},
@@ -125,6 +128,7 @@ class ZmSettingsView( View, IntegrationHelperMixin ):
request.POST,
request.FILES,
instance = integration,
+ prefix = f'integration-{integration.id}',
)
if not integration_attribute_formset.is_valid():
context = {
diff --git a/src/hi/static/js/antinode.js b/src/hi/static/js/antinode.js
index 901a8c1b..2b83865e 100644
--- a/src/hi/static/js/antinode.js
+++ b/src/hi/static/js/antinode.js
@@ -65,7 +65,7 @@
// will be called after each async content update after all updated are
// handled.
//
-// You can use the following atributes on a form/link with the data-async
+// You can use the following attributes on a form/link with the data-async
// attribute. These allow you to show or hide content when the async
// submission/click is triggered.
//