Skip to content

Commit

Permalink
feat(model): add FilePathField for static file (logo) path
Browse files Browse the repository at this point in the history
  • Loading branch information
FraCata00 committed Apr 15, 2024
1 parent ae6b6b5 commit 80a3bf7
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
1 change: 1 addition & 0 deletions admin_interface/admin.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ class ThemeAdmin(admin.ModelAdmin):
"logo_max_height",
"logo_color",
"logo_visible",
"static_logo_path",
),
},
),
Expand Down
24 changes: 24 additions & 0 deletions admin_interface/migrations/0031_theme_static_logo_path.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Generated by Django 5.0.3 on 2024-03-19 22:29

import admin_interface.models
from django.db import migrations, models


class Migration(migrations.Migration):
dependencies = [
("admin_interface", "0030_theme_collapsible_stacked_inlines_and_more"),
]

operations = [
migrations.AddField(
model_name="theme",
name="static_logo_path",
field=models.FilePathField(
blank=True,
match="^.*\\.(jpg|jpeg|png|svg)$",
max_length=255,
path=admin_interface.models.static_logo_directory_path,
verbose_name="static logo",
),
),
]
30 changes: 30 additions & 0 deletions admin_interface/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,16 @@
from django.dispatch import receiver
from django.utils.encoding import force_str
from django.utils.translation import gettext_lazy as _
from django.conf import settings
import os

from .cache import del_cached_active_theme


def static_logo_directory_path():
return settings.LOCAL_FILE_DIR


class ThemeQuerySet(models.QuerySet):
def get_active(self):
objs_active_qs = self.filter(active=True)
Expand Down Expand Up @@ -62,6 +68,14 @@ class Theme(models.Model):
verbose_name=_("visible"),
)

static_logo_path = models.FilePathField(
path=static_logo_directory_path,
blank=True,
verbose_name=_("static logo"),
match=r"^.*\.(jpg|jpeg|png|svg)$",
max_length=255,
)

logo = models.FileField(
upload_to="admin-interface/logo/",
blank=True,
Expand Down Expand Up @@ -401,10 +415,26 @@ class Theme(models.Model):

objects = ThemeQuerySet.as_manager()

@property
def static_logo_relative_url(self):
return os.path.relpath(self.static_logo_path, settings.STATIC_ROOT)

def set_active(self):
self.active = True
self.save()

def save(self, *args, **kwargs):
if self.static_logo_path:
# clear cache if static logo path has changed
try:
obj = Theme.objects.get(pk=self.pk)
if obj.static_logo_path != self.static_logo_path:
del_cached_active_theme()
except Theme.DoesNotExist:
pass

super().save(*args, **kwargs)

class Meta:
app_label = "admin_interface"
verbose_name = _("Theme")
Expand Down

0 comments on commit 80a3bf7

Please sign in to comment.