1
Fork 0
yamdl-playground/yamdl_playground/core/models.py

47 lines
1.2 KiB
Python
Raw Normal View History

2023-12-06 23:30:01 +00:00
from django.db import models
2024-03-24 21:59:25 +00:00
import markdown
2024-03-31 15:02:48 +01:00
from django.template import Template
from django.utils.functional import cached_property
2023-12-06 23:30:01 +00:00
2024-01-10 21:59:54 +00:00
class Tag(models.Model):
__yamdl__ = True
slug = models.SlugField(max_length=128, primary_key=True)
content = models.TextField()
2023-12-06 23:30:01 +00:00
class Page(models.Model):
__yamdl__ = True
2024-03-31 15:02:48 +01:00
_template_cache = {}
2023-12-06 23:30:01 +00:00
title = models.CharField(max_length=255)
2024-03-24 21:59:25 +00:00
raw_content = models.TextField()
2023-12-06 23:30:01 +00:00
content = models.TextField()
2024-01-10 21:59:54 +00:00
slug = models.CharField(max_length=128, unique=True, db_index=True, default=None, null=True)
tags = models.ManyToManyField(Tag)
@classmethod
def from_yaml(cls, **data):
tags = data.pop("tags", None)
2024-03-24 21:59:25 +00:00
content = data.pop("content")
data["raw_content"] = content
data["content"] = markdown.markdown(content)
2024-01-10 21:59:54 +00:00
instance = cls.objects.create(**data)
if tags:
instance.tags.set(tags)
return instance
2024-03-31 15:02:48 +01:00
@cached_property
def content_template(self):
if (cached_template := self._template_cache.get(self.slug)) is None:
cached_template = self._template_cache[self.slug] = Template(self.content, name=self.slug)
return cached_template