keywords work SOMEHOW

This commit is contained in:
Christoph J. Scherr 2023-10-02 01:41:50 +02:00
parent b269b452fd
commit 3be2f095c0
6 changed files with 58 additions and 20 deletions

View File

@ -5,6 +5,7 @@ Desc: Brief intro to Bash Arrays
Date: 2023-09-29
Keywords: bash
technology
test
Category: Test
Featured: True
Public: True

View File

@ -68,11 +68,11 @@ class BlogPost(Searchable):
DATA_DIR = "/app/blog/data/articles"
DEFAULT_LANGS = {'en': False, 'de': False}
def key_words(self) -> bool:
def has_keywords(self) -> bool:
"""
check if the post has keywords
"""
return False
return self.keywords.first() is not None
def regenerate(self):
"""
@ -104,6 +104,8 @@ class BlogPost(Searchable):
try:
# NOTE: MD.Meta is generated after MD.convert() by the meta
# extension.
# Meta not being shown is a reported issue:
# https://github.com/Python-Markdown/markdown/issues/1383
if not hasattr(MD, 'Meta'):
logger.error("Metadata extension for markdown\
not loaded")
@ -118,7 +120,6 @@ class BlogPost(Searchable):
self.public = meta_en["public"][0] == "True"
if "thumbnail" in meta_en:
self.thumbnail = meta_en["thumbnail"][0]
# TODO: parse keywords from markdown
try:
category: Category = Category.objects.get(
@ -126,19 +127,19 @@ class BlogPost(Searchable):
except Category.DoesNotExist:
category = Category.objects.create(
name=meta_en['category'], slug=meta_en['category'])
logger.debug(f"category of {self}: {category}")
self.category = category
# NOTE: we need to save before we can use the manytomany
# logic.
self.save()
for item in meta_en["keywords"]:
try:
keyword: Keyword = Keyword.objects.get(
slug=item)
self.keywords.add(Keyword.objects.get(slug=item))
except Keyword.DoesNotExist:
keyword = Keyword.objects.create(
self.keywords.create(
slug=item, text_en=item, text_de=item)
logger.debug(f"keywords of '{self}': {self.keywords}")
except Exception as e:
logger.warning(
f"could not generate metadata {self.slug} from markdown: {e}")
@ -161,6 +162,8 @@ class BlogPost(Searchable):
try:
# NOTE: MD.Meta is generated after MD.convert() by the meta
# extension.
# Meta not being shown is a reported issue:
# https://github.com/Python-Markdown/markdown/issues/1383
if not hasattr(MD, 'Meta'):
logger.error("Metadata extension for markdown\
not loaded")
@ -173,12 +176,27 @@ class BlogPost(Searchable):
# TODO: parse date from markdown
self.featured = meta_de["featured"][0] == "True"
self.public = meta_de["public"][0] == "True"
# self.thumbnail = meta_de["thumbnail"]
# TODO: parse keywords from markdown
# TODO: parse category from markdown
if "thumbnail" in meta_de:
self.thumbnail = meta_de["thumbnail"][0]
# if keyword or category do not exist, create them
# I suppose
try:
category: Category = Category.objects.get(
slug=meta_de['category'][0])
except Category.DoesNotExist:
category = Category.objects.create(
name=meta_de['category'], slug=meta_de['category'])
self.category = category
# NOTE: we need to save before we can use the manytomany
# logic.
self.save()
for item in meta_de["keywords"]:
try:
self.keywords.add(Keyword.objects.get(slug=item))
except Keyword.DoesNotExist:
self.keywords.create(
slug=item, text_en=item, text_de=item)
logger.debug(f"keywords of '{self}': {self.keywords}")
except Exception as e:
logger.warning(
f"could not generate metadata {self.slug} from markdown: {e}")
@ -191,8 +209,9 @@ class BlogPost(Searchable):
except Exception as e:
logger.warning(
f"could not generate article {self.slug} from markdown: {e}")
self.save()
def get_langs(self) -> dict[str, bool] | None:
def get_langs(self) -> dict[str, bool]:
"""
get available languages
"""
@ -207,7 +226,7 @@ class BlogPost(Searchable):
except ValueError as e:
logger.error(
f"could not safely evaluate 'langs' for '{self}': {e}")
return None
raise e
def set_langs(self, langs: dict[str, bool]):
"""
@ -215,7 +234,7 @@ class BlogPost(Searchable):
"""
self.langs = langs.__repr__()
@classmethod
@ classmethod
def sync_all(cls):
"""
Sync all Blog Posts with the filesystem.

View File

@ -0,0 +1,18 @@
# Generated by Django 3.2.21 on 2023-10-01 23:14
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('start', '0013_keyword_slug'),
]
operations = [
migrations.AlterField(
model_name='searchable',
name='keywords',
field=models.ManyToManyField(blank=True, to='start.Keyword'),
),
]

View File

@ -21,7 +21,7 @@ class Keyword(models.Model):
text_en = models.CharField(max_length=40)
def __str__(self):
return f"{{<{self.__class__.__name__}>\"{self.text_en}\"}}"
return f"{{<{self.__class__.__name__}>\"{self.slug}\"}}"
class Meta:
verbose_name = _("Keyword")
@ -45,7 +45,7 @@ class Searchable(models.Model):
blank=True, max_length=250, unique=False, default="Description EN")
# may be empty/blank for some entries
date = models.DateField(blank=True, null=True)
keywords = models.ManyToManyField(Keyword)
keywords = models.ManyToManyField(Keyword, blank=True)
suburl = models.CharField(max_length=200, blank=True, null=True)
public = models.BooleanField(default=False)

View File

@ -21,8 +21,6 @@ def change_lang(context, lang="de", *args, **kwargs):
"""
logger = logging.getLogger(__name__)
logger.debug(f"changing lang from '{lang}'")
try:
path = context['request'].get_raw_uri()
url = path

2
shell.sh Executable file
View File

@ -0,0 +1,2 @@
#!/bin/bash
docker compose exec -it main python manage.py shell