Skip to content

Home Information - Your home, your data, organized.

Python

Feature/130 Restoring Deleted Attributes (#251)

Thiago Trautwein Santosa3108fa40c6c
diff --git a/src/hi/apps/attribute/edit_context.py b/src/hi/apps/attribute/edit_context.py
index 0339835b..6a139b41 100644
--- a/src/hi/apps/attribute/edit_context.py
+++ b/src/hi/apps/attribute/edit_context.py
@@ -32,7 +32,7 @@ from django.db.models import Model
from hi.constants import DIVID
from .forms import AttributeUploadForm
-from .models import AttributeModel
+from .models import AttributeModel, SoftDeleteAttributeModel
class AttributePageEditContext:
@@ -88,6 +88,10 @@ class AttributePageEditContext:
def restore_url_name(self) -> str:
""" Should be a view that uses AttributeEditViewMixin.post_restore() """
return f'{self.owner_type}_attribute_restore_inline'
+
+ @property
+ def restore_deleted_url_name(self) -> str:
+ return f'{self.owner_type}_attribute_restore_deleted_inline'
@property
def restore_subsystem_url_name(self) -> str:
@@ -149,7 +153,7 @@ class AttributeItemEditContext( AttributePageEditContext ):
return
@property
- def attribute_model_subclass(self) -> Type[AttributeModel]:
+ def attribute_model_subclass(self) -> Type[AttributeModel | SoftDeleteAttributeModel]:
raise NotImplementedError('Subclasses must override this method')
@property
@@ -174,6 +178,16 @@ class AttributeItemEditContext( AttributePageEditContext ):
the owner model. """
return self.owner.attributes.all()
+ def soft_deleted_attributes_queryset(self):
+ """Return queryset with deleted attributes for this owner."""
+
+ if not self.attribute_model_subclass.supports_soft_delete:
+ return self.attribute_model_subclass.objects.none()
+
+ return self.attribute_model_subclass.deleted_objects.filter(
+ **{self.owner_type: self.owner}
+ )
+
@property
def attribute_upload_form_class(self) -> Type[AttributeUploadForm]:
return None
diff --git a/src/hi/apps/attribute/edit_form_handler.py b/src/hi/apps/attribute/edit_form_handler.py
index 7d7f8c37..c2628221 100644
--- a/src/hi/apps/attribute/edit_form_handler.py
+++ b/src/hi/apps/attribute/edit_form_handler.py
@@ -35,6 +35,11 @@ class AttributeEditFormHandler:
file_attributes: QuerySet[AttributeModel] = attr_item_context.attributes_queryset().filter(
value_type_str = str( AttributeValueType.FILE )
).order_by('id')
+
+ deleted_attributes = attr_item_context.soft_deleted_attributes_queryset().order_by(
+ '-updated_datetime',
+ '-id',
+ )
# Regular attributes formset (should exclude FILE attributes)
regular_attributes_formset = attr_item_context.create_regular_attributes_formset(
@@ -43,6 +48,7 @@ class AttributeEditFormHandler:
return AttributeEditFormData(
owner_form = owner_form,
file_attributes = file_attributes,
+ deleted_attributes = deleted_attributes,
regular_attributes_formset = regular_attributes_formset,
)
@@ -93,8 +99,8 @@ class AttributeEditFormHandler:
continue
try:
file_attribute = AttributeModelClass.objects.get(
- id = attr_id,
- value_type_str = str(AttributeValueType.FILE)
+ id = attr_id,
+ value_type_str = str( AttributeValueType.FILE ),
)
# Verify permission to delete
if file_attribute.attribute_type.can_delete:
@@ -131,7 +137,7 @@ class AttributeEditFormHandler:
attribute_id: int = int(attribute_id_str)
attribute = AttributeModelClass.objects.get(
id = attribute_id,
- value_type_str = str(AttributeValueType.FILE)
+ value_type_str = str( AttributeValueType.FILE ),
)
# Clean and validate the new title
new_title = new_title.strip()
diff --git a/src/hi/apps/attribute/edit_response_renderer.py b/src/hi/apps/attribute/edit_response_renderer.py
index 4166b94d..6e45ef77 100644
--- a/src/hi/apps/attribute/edit_response_renderer.py
+++ b/src/hi/apps/attribute/edit_response_renderer.py
@@ -159,6 +159,8 @@ class AttributeEditResponseRenderer:
edit_form_data.regular_attributes_formset = fresh_form_data.regular_attributes_formset
if edit_form_data.file_attributes is None:
edit_form_data.file_attributes = fresh_form_data.file_attributes
+ if edit_form_data.deleted_attributes is None:
+ edit_form_data.deleted_attributes = fresh_form_data.deleted_attributes
return edit_form_data
def render_upload_form(
diff --git a/src/hi/apps/attribute/edit_template_context_builder.py b/src/hi/apps/attribute/edit_template_context_builder.py
index feb52534..f127fd61 100644
--- a/src/hi/apps/attribute/edit_template_context_builder.py
+++ b/src/hi/apps/attribute/edit_template_context_builder.py
@@ -25,6 +25,7 @@ class AttributeEditTemplateContextBuilder:
context = {
'owner_form': edit_form_data.owner_form,
'file_attributes': edit_form_data.file_attributes,
+ 'deleted_attributes': edit_form_data.deleted_attributes,
'regular_attributes_formset': edit_form_data.regular_attributes_formset,
# Duplicate with explicit naming for convenience.
@@ -54,6 +55,7 @@ class AttributeEditTemplateContextBuilder:
context = {
'owner_form': edit_form_data.owner_form,
'file_attributes': edit_form_data.file_attributes,
+ 'deleted_attributes': edit_form_data.deleted_attributes,
'regular_attributes_formset': edit_form_data.regular_attributes_formset,
'success_message': success_message,
'error_message': error_message,
diff --git a/src/hi/apps/attribute/forms.py b/src/hi/apps/attribute/forms.py
index 49e9f98e..576e7b64 100644
--- a/src/hi/apps/attribute/forms.py
+++ b/src/hi/apps/attribute/forms.py
@@ -18,11 +18,14 @@ class RegularAttributeBaseFormSet(forms.BaseInlineFormSet):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Apply filtering after parent initialization
- self.queryset = self.queryset.exclude(value_type_str=str(AttributeValueType.FILE))
+ self.queryset = self._filter_editable_queryset(self.queryset)
def get_queryset(self):
"""Override to automatically filter out FILE attributes"""
queryset = super().get_queryset()
+ return self._filter_editable_queryset(queryset)
+
+ def _filter_editable_queryset(self, queryset):
return queryset.exclude(value_type_str=str(AttributeValueType.FILE))
diff --git a/src/hi/apps/attribute/managers.py b/src/hi/apps/attribute/managers.py
new file mode 100644
index 00000000..ebd48817
--- /dev/null
+++ b/src/hi/apps/attribute/managers.py
@@ -0,0 +1,15 @@
+from django.db import models
+
+
+class ActiveAttributeManager( models.Manager ):
+ """Default manager that hides soft-deleted attributes."""
+
+ def get_queryset( self ):
+ return super().get_queryset().filter( is_deleted = False )
+
+
+class DeletedAttributeManager( models.Manager ):
+ """Manager that returns only soft-deleted attributes."""
+
+ def get_queryset( self ):
+ return super().get_queryset().filter( is_deleted = True )
diff --git a/src/hi/apps/attribute/models.py b/src/hi/apps/attribute/models.py
index a08bd75b..81b1aaea 100644
--- a/src/hi/apps/attribute/models.py
+++ b/src/hi/apps/attribute/models.py
@@ -13,40 +13,15 @@ from .enums import (
AttributeValueType,
AttributeType,
)
+from .managers import ActiveAttributeManager, DeletedAttributeManager
logger = logging.getLogger(__name__)
-class AttributeValueHistoryModel(models.Model):
- """
- Abstract base class for tracking attribute value changes.
- Each concrete attribute subclass should have its own history model
- that defines the foreign key to its specific attribute type.
-
- Only tracks value-based attributes (Text, Boolean, Integer, Float, etc.).
- File attributes are excluded and will be handled separately.
- """
-
- class Meta:
- abstract = True
- ordering = ['-changed_datetime']
-
- value = models.TextField(
- 'Value',
- blank=True, null=True,
- )
- changed_datetime = models.DateTimeField(
- 'Changed',
- auto_now_add=True,
- db_index=True,
- )
-
- def __str__(self):
- return f'Changed at {self.changed_datetime}'
-
-
class AttributeModel(models.Model):
+ supports_soft_delete = False
+
class Meta:
abstract = True
ordering = ['order_id', 'id']
@@ -183,7 +158,8 @@ class AttributeModel(models.Model):
self.file_value.field.upload_to = self.get_upload_to()
if not self.value:
self.value = self.file_value.name
- if not self.pk or not self.__class__.objects.filter( pk = self.pk ).exists():
+ all_manager = getattr( self.__class__, 'all_objects', self.__class__.objects )
+ if not self.pk or not all_manager.filter( pk = self.pk ).exists():
self.file_value.name = generate_unique_filename( self.file_value.name )
# Save the attribute first
@@ -207,7 +183,7 @@ class AttributeModel(models.Model):
attribute=self,
value=self.value
)
-
+
def _get_history_model_class(self):
"""
Get the corresponding history model class for this attribute type.
@@ -234,3 +210,71 @@ class AttributeModel(models.Model):
super().delete( *args, **kwargs )
return
+
+
+class SoftDeleteAttributeModel(AttributeModel):
+ """Base class for attribute models that support soft delete."""
+
+ supports_soft_delete = True
+
+ is_deleted = models.BooleanField(
+ 'Deleted?',
+ default = False,
+ db_index = True,
+ )
+
+ objects = ActiveAttributeManager()
+ all_objects = models.Manager()
+ deleted_objects = DeletedAttributeManager()
+
+ class Meta(AttributeModel.Meta):
+ abstract = True
+
+ def soft_delete( self ):
+ self.is_deleted = True
+ self.save(
+ update_fields = ['is_deleted', 'updated_datetime'],
+ track_history = False,
+ )
+
+ def restore_from_deleted( self ):
+ self.is_deleted = False
+ self.save(
+ update_fields = ['is_deleted', 'updated_datetime'],
+ track_history = False,
+ )
+
+ def delete( self, *args, **kwargs ):
+ hard_delete = kwargs.pop( 'hard_delete', False )
+ if hard_delete:
+ return super().delete(*args, **kwargs)
+ self.soft_delete()
+ return (1, {self.__class__.__name__: 1})
+
+
+class AttributeValueHistoryModel(models.Model):
+ """
+ Abstract base class for tracking attribute value changes.
+ Each concrete attribute subclass should have its own history model
+ that defines the foreign key to its specific attribute type.
+
+ Only tracks value-based attributes (Text, Boolean, Integer, Float, etc.).
+ File attributes are excluded and will be handled separately.
+ """
+
+ class Meta:
+ abstract = True
+ ordering = ['-changed_datetime']
+
+ value = models.TextField(
+ 'Value',
+ blank=True, null=True,
+ )
+ changed_datetime = models.DateTimeField(
+ 'Changed',
+ auto_now_add=True,
+ db_index=True,
+ )
+
+ def __str__(self):
+ return f'Changed at {self.changed_datetime}'
diff --git a/src/hi/apps/attribute/templates/attribute/components/deleted_attribute_list.html b/src/hi/apps/attribute/templates/attribute/components/deleted_attribute_list.html
new file mode 100644
index 00000000..f4153966
--- /dev/null
+++ b/src/hi/apps/attribute/templates/attribute/components/deleted_attribute_list.html
@@ -0,0 +1,29 @@
+{% load icons attribute_extras %}
+{% if deleted_attributes %}
+<div class="attr-v2-attribute-section mt-2">
+ <button type="button"
+ class="btn btn-sm btn-outline-secondary"
+ onclick="window.Hi.toggleDetails('{{ attr_item_context.owner_type }}-deleted-attributes-{{ attr_item_context.owner_id }}')"
+ title="Show deleted attributes">
+ {% icon "history" size="sm" css_class="hi-icon-left" %}Deleted Attributes ({{ deleted_attributes|length }})
+ </button>
+
+ <div id="{{ attr_item_context.owner_type }}-deleted-attributes-{{ attr_item_context.owner_id }}"
+ class="mt-2"
+ style="display: none;">
+ {% for attribute in deleted_attributes %}
+ <div class="d-flex justify-content-between align-items-center border rounded p-2 mb-2">
+ <div>
+ <div><strong>{{ attribute.name }}</strong></div>
+ <div class="text-muted small">{{ attribute.value|attribute_preview }}</div>
+ </div>
+ <a href="{% attr_restore_deleted_url attr_item_context attribute.id %}"
+ class="btn btn-xs btn-outline-primary {{ DIVID.ATTR_V2_RESTORE_LINK_CLASS }}"
+ title="Restore attribute">
+ Restore
+ </a>
+ </div>
+ {% endfor %}
+ </div>
+</div>
+{% endif %}
diff --git a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
index 97023eac..751daffd 100644
--- a/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
+++ b/src/hi/apps/attribute/templates/attribute/components/edit_content_body.html
@@ -111,6 +111,7 @@ by using the AttributeItemEditContext pattern.
<!-- Additional Sections -->
{% block additional_sections %}
+ {% include "attribute/components/deleted_attribute_list.html" with deleted_attributes=deleted_attributes %}
{% endblock %}
</div>
diff --git a/src/hi/apps/attribute/templatetags/attribute_extras.py b/src/hi/apps/attribute/templatetags/attribute_extras.py
index 45db9723..c7f72d84 100644
--- a/src/hi/apps/attribute/templatetags/attribute_extras.py
+++ b/src/hi/apps/attribute/templatetags/attribute_extras.py
@@ -150,6 +150,18 @@ def attr_restore_url(attr_item_context, attribute_id, history_id):
return reverse(url_name, kwargs=params)
+def attr_restore_deleted_url(attr_item_context, attribute_id):
+ """Generate URL for restoring soft-deleted attributes."""
+ from django.urls import reverse
+ url_name = attr_item_context.restore_deleted_url_name
+ params = {
+ attr_item_context.owner_id_param_name: attr_item_context.owner_id,
+ 'attribute_id': attribute_id,
+ }
+ return reverse(url_name, kwargs=params)
+
+
@register.simple_tag
def attr_restore_subsystem_url(attr_item_context):
"""
diff --git a/src/hi/apps/attribute/tests/test_edit_context.py b/src/hi/apps/attribute/tests/test_edit_context.py
index 101aa1f1..a22d7b8a 100644
--- a/src/hi/apps/attribute/tests/test_edit_context.py
+++ b/src/hi/apps/attribute/tests/test_edit_context.py
@@ -5,6 +5,8 @@ Focuses on high-value business logic: property computation, DOM ID generation,
URL parameter construction, and template context assembly.
"""
import logging
+from unittest.mock import MagicMock
+
from hi.apps.attribute.edit_context import AttributeItemEditContext
from hi.testing.base_test_case import BaseTestCase
@@ -19,6 +21,18 @@ class MockOwner:
self.name = name
+class DummyAttributeItemEditContext(AttributeItemEditContext):
+ """Concrete context used to test base-class soft-delete logic."""
+
+ def __init__(self, owner, owner_type, model_class):
+ self._model_class = model_class
+ super().__init__(owner=owner, owner_type=owner_type)
+
+ @property
+ def attribute_model_subclass(self):
+ return self._model_class
+
+
class TestAttributeItemEditContext(BaseTestCase):
def setUp(self):
@@ -190,4 +204,48 @@ class TestAttributeItemEditContext(BaseTestCase):
self.assertEqual(self.context.history_target_id(attr_id), expected_history)
self.assertEqual(self.context.history_toggle_id(attr_id), expected_toggle)
self.assertEqual(self.context.file_title_field_name(attr_id), expected_field)
+
+ def test_soft_deleted_attributes_queryset_returns_none_for_non_soft_delete_model(self):
+ """Models without soft delete should return an empty queryset-like result."""
+
+ expected_queryset = object()
+
+ class NonSoftDeleteModel:
+ supports_soft_delete = False
+ objects = MagicMock()
+
+ NonSoftDeleteModel.objects.none.return_value = expected_queryset
+
+ context = DummyAttributeItemEditContext(
+ owner=self.mock_owner,
+ owner_type="entity",
+ model_class=NonSoftDeleteModel,
+ )
+
+ queryset = context.soft_deleted_attributes_queryset()
+
+ self.assertIs(queryset, expected_queryset)
+ NonSoftDeleteModel.objects.none.assert_called_once_with()
+
+ def test_soft_deleted_attributes_queryset_filters_deleted_objects_for_soft_delete_model(self):
+ """Models with soft delete should filter deleted objects by the owner relation."""
+
+ expected_queryset = object()
+
+ class SoftDeleteModel:
+ supports_soft_delete = True
+ deleted_objects = MagicMock()
+
+ SoftDeleteModel.deleted_objects.filter.return_value = expected_queryset
+
+ context = DummyAttributeItemEditContext(
+ owner=self.mock_owner,
+ owner_type="entity",
+ model_class=SoftDeleteModel,
+ )
+
+ queryset = context.soft_deleted_attributes_queryset()
+
+ self.assertIs(queryset, expected_queryset)
+ SoftDeleteModel.deleted_objects.filter.assert_called_once_with(entity=self.mock_owner)
diff --git a/src/hi/apps/attribute/tests/test_models.py b/src/hi/apps/attribute/tests/test_models.py
index d227ab7e..6fbfc144 100644
--- a/src/hi/apps/attribute/tests/test_models.py
+++ b/src/hi/apps/attribute/tests/test_models.py
@@ -1,9 +1,12 @@
import json
import logging
+import uuid
from unittest.mock import patch
from hi.apps.attribute.models import AttributeModel
from hi.apps.attribute.enums import AttributeValueType, AttributeType
+from hi.apps.entity.enums import EntityType
+from hi.apps.entity.models import Entity, EntityAttribute
from hi.integrations.transient_models import IntegrationKey
from hi.testing.base_test_case import BaseTestCase
@@ -226,3 +229,56 @@ class TestAttributeModel(BaseTestCase):
self.assertEqual(repr(attr), str(attr))
return
+
+class TestSoftDeleteAttributeModelIntegration(BaseTestCase):
+ """Integration tests for soft-delete behavior on concrete attribute models."""
+
+ def _create_entity(self) -> Entity:
+ unique_id = str(uuid.uuid4())[:8]
+ return Entity.objects.create(
+ name='Soft Delete Entity',
+ integration_id=f'test.soft.delete.{unique_id}',
+ integration_name='test_integration',
+ entity_type_str=str(EntityType.LIGHT),
+ )
+
+ def _create_text_attribute(self, entity: Entity, value: str = 'value') -> EntityAttribute:
+ return EntityAttribute.objects.create(
+ entity=entity,
+ name='test_attribute',
+ value=value,
+ attribute_type_str=str(AttributeType.CUSTOM),
+ value_type_str=str(AttributeValueType.TEXT),
+ )
+
+ def test_soft_delete_hides_from_active_manager_and_keeps_deleted_record(self):
+ entity = self._create_entity()
+ attribute = self._create_text_attribute(entity)
+
+ attribute.delete()
+
+ self.assertFalse(EntityAttribute.objects.filter(id=attribute.id).exists())
+ self.assertTrue(EntityAttribute.deleted_objects.filter(id=attribute.id).exists())
+ self.assertTrue(EntityAttribute.all_objects.filter(id=attribute.id).exists())
+
+ def test_restore_from_deleted_makes_attribute_visible_again(self):
+ entity = self._create_entity()
+ attribute = self._create_text_attribute(entity)
+
+ attribute.delete()
+ attribute.restore_from_deleted()
+
+ restored = EntityAttribute.objects.get(id=attribute.id)
+ self.assertFalse(restored.is_deleted)
+ self.assertFalse(EntityAttribute.deleted_objects.filter(id=attribute.id).exists())
+
+ def test_hard_delete_removes_row_from_all_managers(self):
+ entity = self._create_entity()
+ attribute = self._create_text_attribute(entity)
+
+ attribute.delete(hard_delete=True)
+
+ self.assertFalse(EntityAttribute.objects.filter(id=attribute.id).exists())
+ self.assertFalse(EntityAttribute.deleted_objects.filter(id=attribute.id).exists())
+ self.assertFalse(EntityAttribute.all_objects.filter(id=attribute.id).exists())
+
diff --git a/src/hi/apps/attribute/transient_models.py b/src/hi/apps/attribute/transient_models.py
index 5eefbb6b..0f4cbfa0 100644
--- a/src/hi/apps/attribute/transient_models.py
+++ b/src/hi/apps/attribute/transient_models.py
@@ -12,6 +12,7 @@ from .models import AttributeModel
class AttributeEditFormData:
owner_form : ModelForm
file_attributes : QuerySet[AttributeModel]
+ deleted_attributes : QuerySet[AttributeModel]
regular_attributes_formset : BaseInlineFormSet
error_count : int = 0
@@ -32,6 +33,10 @@ class AttributeMultiEditFormData:
@property
def file_attributes(self) -> QuerySet[AttributeModel]:
return self.edit_form_data.file_attributes
+
+ @property
+ def deleted_attributes(self) -> QuerySet[AttributeModel]:
+ return self.edit_form_data.deleted_attributes
@property
def context(self):
diff --git a/src/hi/apps/entity/admin.py b/src/hi/apps/entity/admin.py
index 4da6f39b..9ff6beff 100644
--- a/src/hi/apps/entity/admin.py
+++ b/src/hi/apps/entity/admin.py
@@ -11,6 +11,9 @@ class EntityAttributeInLine(admin.TabularInline):
extra = 0
show_change_link = True
+ def get_queryset( self, request ):
+ return self.model.all_objects.all()
+
class EntityAttributeHistoryInLine(admin.TabularInline):
model = models.EntityAttributeHistory
@@ -128,17 +131,22 @@ class EntityStateDelegationAdmin(admin.ModelAdmin):
class EntityAttributeAdmin(admin.ModelAdmin):
show_full_result_count = False
-
+
list_display = (
'entity',
'name',
'value',
'value_type_str',
'attribute_type_str',
+ 'is_deleted',
'created_datetime',
)
+ list_filter = ( 'is_deleted', )
search_fields = ['name', 'entity__name']
readonly_fields = ('entity', 'created_datetime')
inlines = [EntityAttributeHistoryInLine]
+
+ def get_queryset( self, request ):
+ return self.model.all_objects.all()
diff --git a/src/hi/apps/entity/migrations/0012_add_entityattribute_is_deleted.py b/src/hi/apps/entity/migrations/0012_add_entityattribute_is_deleted.py
new file mode 100644
index 00000000..4c1ab4d7
--- /dev/null
+++ b/src/hi/apps/entity/migrations/0012_add_entityattribute_is_deleted.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.25 on 2026-03-05 10:33
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("entity", "0011_entity_can_add_custom_attributes"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="entityattribute",
+ name="is_deleted",
+ field=models.BooleanField(
+ db_index=True, default=False, verbose_name="Deleted?"
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/entity/models.py b/src/hi/apps/entity/models.py
index 86bfce5b..6075d72e 100644
--- a/src/hi/apps/entity/models.py
+++ b/src/hi/apps/entity/models.py
@@ -10,7 +10,7 @@ from hi.apps.location.models import (
LocationItemPathModel,
LocationView,
)
-from hi.apps.attribute.models import AttributeModel, AttributeValueHistoryModel
+from hi.apps.attribute.models import SoftDeleteAttributeModel, AttributeValueHistoryModel
from hi.integrations.models import IntegrationDetailsModel
from hi.enums import ItemType
@@ -100,7 +100,7 @@ class Entity( IntegrationDetailsModel, LocationItemModelMixin ):
return attribute_map
-class EntityAttribute( AttributeModel ):
+class EntityAttribute( SoftDeleteAttributeModel ):
"""
- Information related to an entity, e.g., specs, docs, notes, configs
- The 'attribute type' is used to help define what information the user might need to provide.
@@ -112,7 +112,7 @@ class EntityAttribute( AttributeModel ):
verbose_name = 'Entity',
on_delete = models.CASCADE,
)
-
+
class Meta:
verbose_name = 'Attribute'
verbose_name_plural = 'Attributes'
@@ -466,4 +466,3 @@ class EntityAttributeHistory(AttributeValueHistoryModel):
indexes = [
models.Index(fields=['attribute', '-changed_datetime']),
]
-
diff --git a/src/hi/apps/entity/tests/test_attribute_history.py b/src/hi/apps/entity/tests/test_attribute_history.py
index 1cde05a2..bd91451d 100644
--- a/src/hi/apps/entity/tests/test_attribute_history.py
+++ b/src/hi/apps/entity/tests/test_attribute_history.py
@@ -112,7 +112,7 @@ class EntityAttributeHistoryTestCase(BaseTestCase):
return
def test_attribute_history_cascade_deletion(self):
- """Test that history records are deleted when attribute is deleted - database constraint behavior."""
+ """Test that history records are deleted when attribute is hard-deleted - database constraint behavior."""
# Create entity and attribute with history
entity = Entity.objects.create(
name='Test Entity',
@@ -137,14 +137,40 @@ class EntityAttributeHistoryTestCase(BaseTestCase):
history_count = EntityAttributeHistory.objects.filter(attribute=attr).count()
self.assertEqual(history_count, 2)
- # Delete the attribute
- attr.delete()
+ # Hard-delete the attribute to trigger FK cascade.
+ attr.delete(hard_delete=True)
# Verify all history records are deleted (cascade)
history_count = EntityAttributeHistory.objects.filter(attribute=attr).count()
self.assertEqual(history_count, 0)
return
+ def test_attribute_history_preserved_on_soft_delete(self):
+ """Test that soft delete keeps history records because row is not physically removed."""
+ entity = Entity.objects.create(
+ name='Test Entity',
+ entity_type_str=str(EntityType.OTHER),
+ integration_id='test.entity',
+ integration_name='test_integration'
+ )
+
+ attr = EntityAttribute.objects.create(
+ entity=entity,
+ name='test_attr',
+ value='test_value',
+ value_type_str=str(AttributeValueType.TEXT),
+ attribute_type_str=str(AttributeType.CUSTOM)
+ )
+
+ attr.value = 'updated_value'
+ attr.save()
+
+ self.assertEqual(EntityAttributeHistory.objects.filter(attribute=attr).count(), 2)
+
+ attr.delete()
+
+ self.assertEqual(EntityAttributeHistory.objects.filter(attribute=attr).count(), 2)
+
def test_multiple_attribute_updates_create_sequential_history(self):
"""Test that multiple updates create proper history sequence - workflow verification."""
# Create entity and attribute
diff --git a/src/hi/apps/entity/tests/test_attribute_soft_delete.py b/src/hi/apps/entity/tests/test_attribute_soft_delete.py
new file mode 100644
index 00000000..bb3f6566
--- /dev/null
+++ b/src/hi/apps/entity/tests/test_attribute_soft_delete.py
@@ -0,0 +1,82 @@
+import logging
+
+from django.urls import reverse
+
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.entity.models import EntityAttribute
+from hi.testing.view_test_base import SyncViewTestCase
+
+from .synthetic_data import EntityAttributeSyntheticData
+
+logging.disable(logging.CRITICAL)
+
+
+class TestEntityAttributeSoftDelete(SyncViewTestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.entity = EntityAttributeSyntheticData.create_test_entity(name='Restore Test Entity')
+ self.attribute = EntityAttribute.objects.create(
+ entity=self.entity,
+ name='manual',
+ value='content',
+ attribute_type_str=str(AttributeType.CUSTOM),
+ value_type_str=str(AttributeValueType.TEXT),
+ )
+
+ def test_restore_deleted_entity_attribute_not_deleted_returns_404(self):
+ """Restoring an active attribute should fail deleted manager lookup."""
+ url = reverse(
+ 'entity_attribute_restore_deleted_inline',
+ kwargs={'entity_id': self.entity.id, 'attribute_id': self.attribute.id},
+ )
+
+ response = self.client.get(url)
+
+ self.assertResponseStatusCode(response, 404)
+ self.attribute.refresh_from_db()
+ self.assertFalse(self.attribute.is_deleted)
+
+ def test_soft_delete_and_restore_model_cycle(self):
+ """Soft delete should hide from active manager and restore should bring it back."""
+ self.attribute.delete()
+
+ self.assertFalse(EntityAttribute.objects.filter(id=self.attribute.id).exists())
+ self.assertTrue(EntityAttribute.deleted_objects.filter(id=self.attribute.id).exists())
+
+ deleted_attr = EntityAttribute.deleted_objects.get(id=self.attribute.id)
+ deleted_attr.restore_from_deleted()
+
+ self.assertTrue(EntityAttribute.objects.filter(id=self.attribute.id).exists())
+ self.assertFalse(EntityAttribute.deleted_objects.filter(id=self.attribute.id).exists())
+
+ def test_restore_deleted_entity_attribute_inline_success(self):
+ """Restore endpoint should recover a previously soft-deleted attribute."""
+ self.attribute.delete()
+ self.assertFalse(EntityAttribute.objects.filter(id=self.attribute.id).exists())
+
+ url = reverse(
+ 'entity_attribute_restore_deleted_inline',
+ kwargs={'entity_id': self.entity.id, 'attribute_id': self.attribute.id},
+ )
+
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ restored = EntityAttribute.objects.get(id=self.attribute.id)
+ self.assertFalse(restored.is_deleted)
+
+ def test_restore_deleted_entity_attribute_wrong_entity_returns_404(self):
+ """Deleted attributes must only be restored through the owning entity endpoint."""
+ other_entity = EntityAttributeSyntheticData.create_test_entity(name='Other Entity')
+ self.attribute.delete()
+
+ url = reverse(
+ 'entity_attribute_restore_deleted_inline',
+ kwargs={'entity_id': other_entity.id, 'attribute_id': self.attribute.id},
+ )
+
+ response = self.client.get(url)
+
+ self.assertResponseStatusCode(response, 404)
+ self.assertTrue(EntityAttribute.deleted_objects.filter(id=self.attribute.id).exists())
diff --git a/src/hi/apps/entity/tests/test_entity_attribute_framework.py b/src/hi/apps/entity/tests/test_entity_attribute_framework.py
index 59d6c351..5d7aa6fd 100644
--- a/src/hi/apps/entity/tests/test_entity_attribute_framework.py
+++ b/src/hi/apps/entity/tests/test_entity_attribute_framework.py
@@ -180,6 +180,32 @@ class EntityAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, Base
# File handling is tested at the view level, but we can test the context setup
self.assertIsNotNone(context.file_upload_url)
+
+ def test_create_edit_form_data_includes_soft_deleted_attributes(self):
+ """Deleted attributes should be available for restore in the edit form payload."""
+ entity = self.create_owner_instance(name="Soft Delete Form Data Entity")
+ active_attr = self.create_attribute_instance(
+ entity,
+ name="active_attr",
+ value="active",
+ value_type_str=str(AttributeValueType.TEXT),
+ )
+ deleted_attr = self.create_attribute_instance(
+ entity,
+ name="deleted_attr",
+ value="deleted",
+ value_type_str=str(AttributeValueType.TEXT),
+ )
+ deleted_attr.delete()
+
+ context = self.create_item_edit_context(entity)
+ handler = self._get_handler()
+
+ form_data = handler.create_edit_form_data(attr_item_context=context)
+ deleted_ids = [attr.id for attr in form_data.deleted_attributes]
+
+ self.assertIn(deleted_attr.id, deleted_ids)
+ self.assertNotIn(active_attr.id, deleted_ids)
def _get_handler(self):
"""Get handler instance for testing."""
diff --git a/src/hi/apps/entity/tests/test_views.py b/src/hi/apps/entity/tests/test_views.py
index 4e873d83..d6a7c6a6 100644
--- a/src/hi/apps/entity/tests/test_views.py
+++ b/src/hi/apps/entity/tests/test_views.py
@@ -215,11 +215,30 @@ class TestEntityEditView(DualModeViewTestCase):
self.assertSuccessResponse(response)
- # Verify file was deleted
+ # Verify file is hidden from active querysets
self.assertFalse(
EntityAttribute.objects.filter(id=self.file_attr.id).exists()
)
+ # Verify file attribute is soft-deleted and still recoverable
+ deleted_attr = EntityAttribute.all_objects.get(id=self.file_attr.id)
+ self.assertTrue(deleted_attr.is_deleted)
+
+ def test_restore_deleted_attribute_inline(self):
+ """Test restoring a deleted attribute through inline restore endpoint."""
+ self.file_attr.delete()
+ self.assertFalse(EntityAttribute.objects.filter(id=self.file_attr.id).exists())
+
+ restore_url = reverse(
+ 'entity_attribute_restore_deleted_inline',
+ kwargs={'entity_id': self.entity.id, 'attribute_id': self.file_attr.id},
+ )
+ response = self.client.get(restore_url)
+
+ self.assertSuccessResponse(response)
+ restored = EntityAttribute.objects.get(id=self.file_attr.id)
+ self.assertFalse(restored.is_deleted)
+
def test_post_invalid_form_returns_errors(self):
"""Test that invalid form submission returns error response with form errors."""
url = reverse('entity_edit', kwargs={'entity_id': self.entity.id})
@@ -959,11 +978,16 @@ class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):
self.assertSuccessResponse(response)
- # Verify file was deleted
+ # Verify file is hidden from active querysets
self.assertFalse(
EntityAttribute.objects.filter(id=file_attr.id).exists()
)
+ # Verify file attribute still exists as deleted for restore
+ self.assertTrue(
+ EntityAttribute.deleted_objects.filter(id=file_attr.id).exists()
+ )
+
def test_file_title_update_through_entity_edit(self):
"""Test updating file titles through EntityEditView."""
# Create file attribute
@@ -1035,6 +1059,10 @@ class TestEntityEditViewFileUploadIntegration(DualModeViewTestCase):
self.assertFalse(
EntityAttribute.objects.filter(id=file_to_delete.id).exists()
)
+
+ self.assertTrue(
+ EntityAttribute.deleted_objects.filter(id=file_to_delete.id).exists()
+ )
# Verify title update occurred
file_to_update.refresh_from_db()
diff --git a/src/hi/apps/entity/urls.py b/src/hi/apps/entity/urls.py
index 1f0e489d..50acb884 100644
--- a/src/hi/apps/entity/urls.py
+++ b/src/hi/apps/entity/urls.py
@@ -29,6 +29,10 @@ urlpatterns = [
views.EntityAttributeRestoreInlineView.as_view(),
name='entity_attribute_restore_inline' ),
+ re_path( r'^attribute/restore-deleted/(?P<entity_id>\d+)/(?P<attribute_id>\d+)/$',
+ views.EntityAttributeRestoreDeletedInlineView.as_view(),
+ name='entity_attribute_restore_deleted_inline' ),
+
re_path( r'^edit/', include('hi.apps.entity.edit.urls' )),
]
diff --git a/src/hi/apps/entity/views.py b/src/hi/apps/entity/views.py
index 36b83e48..19f1eaa2 100644
--- a/src/hi/apps/entity/views.py
+++ b/src/hi/apps/entity/views.py
@@ -5,6 +5,7 @@ from django.http import HttpRequest, HttpResponse
from django.views.generic import View
from hi.apps.attribute.view_mixins import AttributeEditViewMixin
+from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
from hi.apps.control.controller_history_manager import ControllerHistoryManager
from hi.apps.monitor.status_display_manager import StatusDisplayManager
from hi.apps.sense.sensor_history_manager import SensorHistoryMixin
@@ -172,3 +173,30 @@ class EntityAttributeRestoreInlineView( View, AttributeEditViewMixin ):
history_id = history_id,
attr_item_context = attr_item_context,
)
+
+
+class EntityAttributeRestoreDeletedInlineView( View ):
+ """View for restoring soft-deleted EntityAttributes."""
+
+ def get( self,
+ request : HttpRequest,
+ entity_id : int,
+ attribute_id : int,
+ *args : Any,
+ **kwargs : Any ) -> HttpResponse:
+ try:
+ attribute = EntityAttribute.deleted_objects.select_related('entity').get(
+ pk = attribute_id,
+ entity_id = entity_id,
+ )
+ except EntityAttribute.DoesNotExist:
+ return page_not_found_response(request, "Deleted attribute not found.")
+
+ attribute.restore_from_deleted()
+ attr_item_context = EntityAttributeItemEditContext( entity = attribute.entity )
+ renderer = AttributeEditResponseRenderer()
+ return renderer.render_form_success_response(
+ attr_item_context = attr_item_context,
+ request = request,
+ message = 'Attribute restored',
+ )
diff --git a/src/hi/apps/location/admin.py b/src/hi/apps/location/admin.py
index 36b2ce4f..0c6ad868 100644
--- a/src/hi/apps/location/admin.py
+++ b/src/hi/apps/location/admin.py
@@ -14,6 +14,9 @@ class LocationAttributeInLine(admin.TabularInline):
extra = 0
show_change_link = True
+ def get_queryset( self, request ):
+ return self.model.all_objects.all()
+
class LocationAttributeHistoryInLine(admin.TabularInline):
model = models.LocationAttributeHistory
@@ -66,16 +69,21 @@ class LocationViewAdmin(admin.ModelAdmin):
class LocationAttributeAdmin(admin.ModelAdmin):
show_full_result_count = False
-
+
list_display = (
'location',
'name',
'value',
'value_type_str',
'attribute_type_str',
+ 'is_deleted',
'created_datetime',
)
+ list_filter = ( 'is_deleted', )
search_fields = ['name', 'location__name']
readonly_fields = ('location', 'created_datetime')
inlines = [LocationAttributeHistoryInLine]
+
+ def get_queryset( self, request ):
+ return self.model.all_objects.all()
diff --git a/src/hi/apps/location/migrations/0006_add_locationattribute_is_deleted.py b/src/hi/apps/location/migrations/0006_add_locationattribute_is_deleted.py
new file mode 100644
index 00000000..74cfc0f7
--- /dev/null
+++ b/src/hi/apps/location/migrations/0006_add_locationattribute_is_deleted.py
@@ -0,0 +1,20 @@
+# Generated by Django 4.2.25 on 2026-03-05 10:33
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("location", "0005_alter_locationattribute_options"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="locationattribute",
+ name="is_deleted",
+ field=models.BooleanField(
+ db_index=True, default=False, verbose_name="Deleted?"
+ ),
+ ),
+ ]
diff --git a/src/hi/apps/location/models.py b/src/hi/apps/location/models.py
index c4280993..ed86f31e 100644
--- a/src/hi/apps/location/models.py
+++ b/src/hi/apps/location/models.py
@@ -4,7 +4,7 @@ from django.core.files.storage import default_storage
from django.db import models
from hi.apps.common.svg_models import SvgDecimalField, SvgItemPositionBounds, SvgViewBox
-from hi.apps.attribute.models import AttributeModel, AttributeValueHistoryModel
+from hi.apps.attribute.models import SoftDeleteAttributeModel, AttributeValueHistoryModel
from hi.enums import ItemType
from hi.models import ItemTypeModelMixin
@@ -102,7 +102,7 @@ class Location( models.Model, ItemTypeModelMixin ):
return
-class LocationAttribute( AttributeModel ):
+class LocationAttribute( SoftDeleteAttributeModel ):
"""
- Information related to an location, e.g., specs, docs, notes, configs
- The 'attribute type' is used to help define what information the user might need to provide.
@@ -114,7 +114,7 @@ class LocationAttribute( AttributeModel ):
verbose_name = 'Location',
on_delete = models.CASCADE,
)
-
+
class Meta:
verbose_name = 'Attribute'
verbose_name_plural = 'Attributes'
diff --git a/src/hi/apps/location/tests/test_attribute_soft_delete.py b/src/hi/apps/location/tests/test_attribute_soft_delete.py
new file mode 100644
index 00000000..8bca3ac3
--- /dev/null
+++ b/src/hi/apps/location/tests/test_attribute_soft_delete.py
@@ -0,0 +1,86 @@
+import logging
+
+from django.urls import reverse
+
+from hi.apps.attribute.enums import AttributeType, AttributeValueType
+from hi.apps.location.models import Location, LocationAttribute
+from hi.testing.view_test_base import SyncViewTestCase
+
+logging.disable(logging.CRITICAL)
+
+
+class TestLocationAttributeSoftDelete(SyncViewTestCase):
+
+ def setUp(self):
+ super().setUp()
+ self.location = Location.objects.create(
+ name='Restore Test Location',
+ svg_fragment_filename='restore-test.svg',
+ svg_view_box_str='0 0 100 100',
+ )
+ self.attribute = LocationAttribute.objects.create(
+ location=self.location,
+ name='note',
+ value='content',
+ attribute_type_str=str(AttributeType.CUSTOM),
+ value_type_str=str(AttributeValueType.TEXT),
+ )
+
+ def test_restore_deleted_location_attribute_inline(self):
+ self.attribute.delete()
+ self.assertFalse(LocationAttribute.objects.filter(id=self.attribute.id).exists())
+
+ url = reverse(
+ 'location_attribute_restore_deleted_inline',
+ kwargs={'location_id': self.location.id, 'attribute_id': self.attribute.id},
+ )
+ response = self.client.get(url)
+
+ self.assertSuccessResponse(response)
+ restored = LocationAttribute.objects.get(id=self.attribute.id)
+ self.assertFalse(restored.is_deleted)
+
+ def test_soft_delete_and_restore_model_cycle(self):
+ """Soft delete should hide from active manager and restore should bring it back."""
+ self.attribute.delete()
+
+ self.assertFalse(LocationAttribute.objects.filter(id=self.attribute.id).exists())
+ self.assertTrue(LocationAttribute.deleted_objects.filter(id=self.attribute.id).exists())
+
+ deleted_attr = LocationAttribute.deleted_objects.get(id=self.attribute.id)
+ deleted_attr.restore_from_deleted()
+
+ self.assertTrue(LocationAttribute.objects.filter(id=self.attribute.id).exists())
+ self.assertFalse(LocationAttribute.deleted_objects.filter(id=self.attribute.id).exists())
+
+ def test_restore_deleted_location_attribute_not_deleted_returns_404(self):
+ """Restoring an active attribute should return not found for deleted manager lookup."""
+ url = reverse(
+ 'location_attribute_restore_deleted_inline',
+ kwargs={'location_id': self.location.id, 'attribute_id': self.attribute.id},
+ )
+
+ response = self.client.get(url)
+
+ self.assertResponseStatusCode(response, 404)
+ self.attribute.refresh_from_db()
+ self.assertFalse(self.attribute.is_deleted)
+
+ def test_restore_deleted_location_attribute_wrong_location_returns_404(self):
+ """Deleted attributes must only be restored through the owning location endpoint."""
+ other_location = Location.objects.create(
+ name='Other Location',
+ svg_fragment_filename='other-location.svg',
+ svg_view_box_str='0 0 100 100',
+ )
+ self.attribute.delete()
+
+ url = reverse(
+ 'location_attribute_restore_deleted_inline',
+ kwargs={'location_id': other_location.id, 'attribute_id': self.attribute.id},
+ )
+
+ response = self.client.get(url)
+
+ self.assertResponseStatusCode(response, 404)
+ self.assertTrue(LocationAttribute.deleted_objects.filter(id=self.attribute.id).exists())
diff --git a/src/hi/apps/location/tests/test_location_attribute_framework.py b/src/hi/apps/location/tests/test_location_attribute_framework.py
index 962ffbed..e723e27e 100644
--- a/src/hi/apps/location/tests/test_location_attribute_framework.py
+++ b/src/hi/apps/location/tests/test_location_attribute_framework.py
@@ -228,6 +228,32 @@ class LocationAttributeEditFormHandlerTest(AttributeEditFormHandlerTestMixin, Ba
# Should handle long names according to model constraints
is_valid = handler.validate_forms(edit_form_data=edit_form_data)
self.assertIsInstance(is_valid, bool)
+
+ def test_create_edit_form_data_includes_soft_deleted_attributes(self):
+ """Deleted attributes should be available for restore in the edit form payload."""
+ location = self.create_owner_instance(name="Soft Delete Form Data Location")
+ active_attr = self.create_attribute_instance(
+ location,
+ name="active_attr",
+ value="active",
+ value_type_str=str(AttributeValueType.TEXT),
+ )
+ deleted_attr = self.create_attribute_instance(
+ location,
+ name="deleted_attr",
+ value="deleted",
+ value_type_str=str(AttributeValueType.TEXT),
+ )
+ deleted_attr.delete()
+
+ context = self.create_item_edit_context(location)
+ handler = self._get_handler()
+
+ form_data = handler.create_edit_form_data(attr_item_context=context)
+ deleted_ids = [attr.id for attr in form_data.deleted_attributes]
+
+ self.assertIn(deleted_attr.id, deleted_ids)
+ self.assertNotIn(active_attr.id, deleted_ids)
def _get_handler(self):
"""Get handler instance for testing."""
diff --git a/src/hi/apps/location/urls.py b/src/hi/apps/location/urls.py
index a530582f..a5cdc31b 100644
--- a/src/hi/apps/location/urls.py
+++ b/src/hi/apps/location/urls.py
@@ -36,6 +36,10 @@ urlpatterns = [
re_path( r'^attribute/restore/(?P<location_id>\d+)/(?P<attribute_id>\d+)/(?P<history_id>\d+)$',
views.LocationAttributeRestoreInlineView.as_view(),
name='location_attribute_restore_inline'),
+
+ re_path( r'^attribute/restore-deleted/(?P<location_id>\d+)/(?P<attribute_id>\d+)/$',
+ views.LocationAttributeRestoreDeletedInlineView.as_view(),
+ name='location_attribute_restore_deleted_inline'),
re_path( r'^edit/', include('hi.apps.location.edit.urls' )),
diff --git a/src/hi/apps/location/views.py b/src/hi/apps/location/views.py
index a6236156..ca2596c8 100644
--- a/src/hi/apps/location/views.py
+++ b/src/hi/apps/location/views.py
@@ -10,6 +10,7 @@ from hi.apps.common.utils import is_ajax
import hi.apps.common.antinode as antinode
from hi.apps.attribute.view_mixins import AttributeEditViewMixin
+from hi.apps.attribute.edit_response_renderer import AttributeEditResponseRenderer
from hi.apps.control.one_click_control_service import (
OneClickControlService,
OneClickError,
@@ -265,3 +266,30 @@ class LocationAttributeRestoreInlineView( View, AttributeEditViewMixin ):
history_id = history_id,
attr_item_context = attr_item_context,
)
+
+
+class LocationAttributeRestoreDeletedInlineView( View ):
+ """View for restoring soft-deleted LocationAttributes."""
+
+ def get( self,
+ request : HttpRequest,
+ location_id : int,
+ attribute_id : int,
+ *args : Any,
+ **kwargs : Any ) -> HttpResponse:
+ try:
+ attribute = LocationAttribute.deleted_objects.select_related('location').get(
+ pk = attribute_id,
+ location_id = location_id,
+ )
+ except LocationAttribute.DoesNotExist:
+ return page_not_found_response(request, "Deleted attribute not found.")
+
+ attribute.restore_from_deleted()
+ attr_item_context = LocationAttributeItemEditContext( location = attribute.location )
+ renderer = AttributeEditResponseRenderer()
+ return renderer.render_form_success_response(
+ attr_item_context = attr_item_context,
+ request = request,
+ message = 'Attribute restored',
+ )
diff --git a/src/hi/integrations/sync_mixins.py b/src/hi/integrations/sync_mixins.py
index ef88102d..e9d6ff5f 100644
--- a/src/hi/integrations/sync_mixins.py
+++ b/src/hi/integrations/sync_mixins.py
@@ -96,7 +96,10 @@ class IntegrationSyncMixin:
).delete()[0]
logger.debug(f'Removed {removed_state_count} orphaned entity states for {entity}')
- # Remove integration-related attributes (keep user-created ones)
+ # Remove integration-related attributes (keep user-created ones).
+ # Note: queryset .delete() intentionally bypasses the model-level
+ # SoftDeleteAttributeModel.delete() override, performing a hard delete.
+ # Integration attributes should not accumulate as soft-deleted records.
removed_attr_count = entity.attributes.filter(
integration_key_str__isnull=False
).delete()[0]