kioblog 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. kioblog/__init__.py +0 -0
  2. kioblog/admin.py +35 -0
  3. kioblog/apps.py +6 -0
  4. kioblog/context_preprocessors.py +16 -0
  5. kioblog/decorators.py +10 -0
  6. kioblog/management/__init__.py +0 -0
  7. kioblog/management/commands/__init__.py +0 -0
  8. kioblog/management/commands/regenerate_code_css.py +32 -0
  9. kioblog/markdown/__init__.py +0 -0
  10. kioblog/markdown/code_chrome.py +94 -0
  11. kioblog/markdown/pygments_onedark.py +43 -0
  12. kioblog/markdown/render.py +40 -0
  13. kioblog/migrations/0001_initial.py +82 -0
  14. kioblog/migrations/0002_auto_20220724_1836.py +21 -0
  15. kioblog/migrations/0003_auto_20220809_1735.py +23 -0
  16. kioblog/migrations/0004_tag_post_fields.py +44 -0
  17. kioblog/migrations/0005_backfill_published.py +39 -0
  18. kioblog/migrations/0006_post_content_markdownx.py +17 -0
  19. kioblog/migrations/__init__.py +0 -0
  20. kioblog/models.py +135 -0
  21. kioblog/sitemap.py +54 -0
  22. kioblog/static/kioblog/code.css +89 -0
  23. kioblog/static/kioblog/css/custom.css +77 -0
  24. kioblog/templates/kioblog/base.html +31 -0
  25. kioblog/templates/kioblog/home.html +76 -0
  26. kioblog/templates/kioblog/includes/footer.html +6 -0
  27. kioblog/templates/kioblog/includes/header.html +18 -0
  28. kioblog/templates/kioblog/includes/sidebar.html +37 -0
  29. kioblog/templates/kioblog/post.html +56 -0
  30. kioblog/templates/kioblog/search.html +33 -0
  31. kioblog/tests/__init__.py +0 -0
  32. kioblog/tests/base.py +18 -0
  33. kioblog/tests/test_markdown.py +35 -0
  34. kioblog/tests/test_models.py +81 -0
  35. kioblog/tests/test_views.py +103 -0
  36. kioblog/urls.py +42 -0
  37. kioblog/views.py +73 -0
  38. kioblog-0.2.0.dist-info/METADATA +35 -0
  39. kioblog-0.2.0.dist-info/RECORD +42 -0
  40. kioblog-0.2.0.dist-info/WHEEL +5 -0
  41. kioblog-0.2.0.dist-info/licenses/LICENSE.txt +21 -0
  42. kioblog-0.2.0.dist-info/top_level.txt +1 -0
kioblog/__init__.py ADDED
File without changes
kioblog/admin.py ADDED
@@ -0,0 +1,35 @@
1
+ from django.contrib import admin
2
+
3
+ from markdownx.admin import MarkdownxModelAdmin
4
+
5
+ from kioblog import models
6
+
7
+
8
+ class PostAdmin(MarkdownxModelAdmin):
9
+ prepopulated_fields = {"slug": ("title",)}
10
+ filter_horizontal = ('tags',)
11
+ list_display = ('title', 'category', 'published', 'draft', 'is_featured')
12
+
13
+
14
+ class CategoryAdmin(admin.ModelAdmin):
15
+ list_display = ('title', 'slug', 'featured')
16
+
17
+
18
+ class TagAdmin(admin.ModelAdmin):
19
+ list_display = ('title', 'slug')
20
+ prepopulated_fields = {"slug": ("title",)}
21
+
22
+
23
+ class CommentAdmin(admin.ModelAdmin):
24
+ list_display = ('username', 'post', 'parent', 'created')
25
+
26
+
27
+ class MetaAdmin(admin.ModelAdmin):
28
+ list_display = ('key', 'value')
29
+
30
+
31
+ admin.site.register(models.Post, PostAdmin)
32
+ admin.site.register(models.Category, CategoryAdmin)
33
+ admin.site.register(models.Tag, TagAdmin)
34
+ admin.site.register(models.Comment, CommentAdmin)
35
+ admin.site.register(models.Meta, MetaAdmin)
kioblog/apps.py ADDED
@@ -0,0 +1,6 @@
1
+ from django.apps import AppConfig
2
+
3
+
4
+ class KioblogConfig(AppConfig):
5
+ default_auto_field = 'django.db.models.BigAutoField'
6
+ name = 'kioblog'
@@ -0,0 +1,16 @@
1
+ from django.db.models import Count, Q
2
+
3
+ from kioblog import models
4
+
5
+
6
+ def kioblog_settings(request):
7
+ return {
8
+ 'kioblog_settings': {meta.key: meta.value for meta in models.Meta.objects.all()},
9
+ }
10
+
11
+
12
+ def kioblog_categories(request):
13
+ return {
14
+ 'kioblog_categories': models.Category.objects.annotate(
15
+ post_count=Count('post', filter=Q(post__draft=False))),
16
+ }
kioblog/decorators.py ADDED
@@ -0,0 +1,10 @@
1
+ from kioblog import models
2
+
3
+
4
+ def load_recent_posts(view):
5
+ def wrapper(request, *args, **kwargs):
6
+ r = view(request, *args, **kwargs)
7
+ current_slug = kwargs.get('slug', None)
8
+ r.context_data.update({'recent_posts': models.Post.get_recent_posts(current_slug)})
9
+ return r.render()
10
+ return wrapper
File without changes
File without changes
@@ -0,0 +1,32 @@
1
+ """Regenerate the shipped One Dark token stylesheet.
2
+
3
+ Writes ``kioblog/static/kioblog/code.css`` from
4
+ :class:`kioblog.markdown.pygments_onedark.OneDarkStyle` so the ``.highlight``
5
+ token classes always match what the renderer emits. Run after changing the
6
+ style. The file is committed and shipped with the package.
7
+ """
8
+
9
+ from pathlib import Path
10
+
11
+ from django.core.management.base import BaseCommand
12
+ from pygments.formatters import HtmlFormatter
13
+
14
+ from kioblog.markdown.pygments_onedark import OneDarkStyle
15
+
16
+ HEADER = (
17
+ '/* One Dark syntax token colors for kioblog code blocks.\n'
18
+ ' * Generated from kioblog.markdown.pygments_onedark.OneDarkStyle.\n'
19
+ ' * Regenerate with: python manage.py regenerate_code_css\n'
20
+ ' * The code-block chrome (bar, dots, copy button) is styled by the consumer. */\n'
21
+ )
22
+
23
+
24
+ class Command(BaseCommand):
25
+ help = 'Regenerate kioblog/static/kioblog/code.css from the OneDark Pygments style'
26
+
27
+ def handle(self, *args, **options):
28
+ css = HtmlFormatter(style=OneDarkStyle).get_style_defs('.highlight')
29
+ out = Path(__file__).resolve().parents[2] / 'static' / 'kioblog' / 'code.css'
30
+ out.parent.mkdir(parents=True, exist_ok=True)
31
+ out.write_text(HEADER + css + '\n', encoding='utf-8')
32
+ self.stdout.write(self.style.SUCCESS('Wrote {}'.format(out)))
File without changes
@@ -0,0 +1,94 @@
1
+ """Markdown extension that renders fenced code blocks with the kioblog chrome.
2
+
3
+ The DOM structure and class names emitted here are a contract with the
4
+ consumer project (section 5 of SPEC_ericbujeque_blog.md): kioblog *emits* the
5
+ markup, the consumer only styles it. Do not rename classes or change the
6
+ structure without updating that contract.
7
+
8
+ Info-string syntax on the opening fence: ``lang`` or ``lang:path/to/file``.
9
+ Every fenced block gets the chrome; when no language is given it defaults to
10
+ ``text`` and the filename span is omitted when no filename is given.
11
+ """
12
+
13
+ import re
14
+ from html import escape
15
+
16
+ from markdown.extensions import Extension
17
+ from markdown.preprocessors import Preprocessor
18
+ from pygments import highlight
19
+ from pygments.formatters import HtmlFormatter
20
+ from pygments.lexers import get_lexer_by_name
21
+ from pygments.util import ClassNotFound
22
+
23
+ FENCED_BLOCK_RE = re.compile(
24
+ r'^(?P<fence>`{3,})[ ]*(?P<info>[^\n`]*)\n'
25
+ r'(?P<code>.*?)'
26
+ r'(?<=\n)(?P=fence)[ ]*$',
27
+ re.MULTILINE | re.DOTALL,
28
+ )
29
+
30
+
31
+ def _parse_info(info):
32
+ """`python:accounts/views.py` -> ('python', 'accounts/views.py')."""
33
+ info = info.strip()
34
+ if not info:
35
+ return 'text', ''
36
+ lang, _, filename = info.partition(':')
37
+ lang = lang.strip() or 'text'
38
+ return lang, filename.strip()
39
+
40
+
41
+ def _gutter(code):
42
+ lines = code.split('\n')
43
+ return '\n'.join(str(n) for n in range(1, len(lines) + 1))
44
+
45
+
46
+ class CodeChromePreprocessor(Preprocessor):
47
+ def run(self, lines):
48
+ text = '\n'.join(lines)
49
+ while True:
50
+ m = FENCED_BLOCK_RE.search(text)
51
+ if not m:
52
+ break
53
+ html = self._render_block(m.group('info'), m.group('code'))
54
+ placeholder = self.md.htmlStash.store(html)
55
+ text = '{}\n{}\n{}'.format(text[:m.start()], placeholder, text[m.end():])
56
+ return text.split('\n')
57
+
58
+ def _render_block(self, info, code):
59
+ lang, filename = _parse_info(info)
60
+ code = code.rstrip('\n')
61
+
62
+ try:
63
+ lexer = get_lexer_by_name(lang)
64
+ except ClassNotFound:
65
+ lexer = get_lexer_by_name('text')
66
+ highlighted = highlight(
67
+ code, lexer, HtmlFormatter(cssclass='highlight', wrapcode=True),
68
+ ).strip()
69
+
70
+ file_span = ''
71
+ if filename:
72
+ file_span = '<span class="code-block__file">{}</span>'.format(escape(filename))
73
+ gutter = escape(_gutter(code))
74
+
75
+ return (
76
+ '<figure class="code-block" data-lang="{lang}">'
77
+ '<div class="code-block__bar">'
78
+ '<span class="code-block__dots"><i></i><i></i><i></i></span>'
79
+ '{file_span}'
80
+ '<span class="code-block__lang">{lang}</span>'
81
+ '<button class="code-block__copy" type="button">Copy</button>'
82
+ '</div>'
83
+ '<div class="code-block__body">'
84
+ '<pre class="code-block__gutter" aria-hidden="true">{gutter}</pre>'
85
+ '{highlighted}'
86
+ '</div>'
87
+ '</figure>'
88
+ ).format(lang=escape(lang), file_span=file_span, gutter=gutter, highlighted=highlighted)
89
+
90
+
91
+ class CodeChromeExtension(Extension):
92
+ def extendMarkdown(self, md):
93
+ # Priority above fenced_code (25) so we own every fence.
94
+ md.preprocessors.register(CodeChromePreprocessor(md), 'kioblog_code_chrome', 30)
@@ -0,0 +1,43 @@
1
+ """One Dark Pygments style.
2
+
3
+ Single source of truth for the syntax token colors shipped in
4
+ ``kioblog/static/kioblog/code.css`` (regenerate with
5
+ ``python manage.py regenerate_code_css``). The chrome of the code block
6
+ (bar, semaphore dots, copy button) is styled by the consumer project.
7
+ Hex values come from section 5 of SPEC_ericbujeque_blog.md.
8
+ """
9
+
10
+ from pygments.style import Style
11
+ from pygments.token import (
12
+ Comment, Error, Keyword, Name, Number, Operator, Punctuation, String, Token,
13
+ )
14
+
15
+
16
+ class OneDarkStyle(Style):
17
+ name = 'one-dark'
18
+ background_color = '#282c34'
19
+
20
+ styles = {
21
+ Token: '#abb2bf', # base text
22
+ Comment: 'italic #5c6370',
23
+ Keyword: '#c678dd',
24
+ Keyword.Constant: '#d19a66', # True / False / None
25
+ Keyword.Type: '#e5c07b',
26
+ Operator: '#c678dd',
27
+ Punctuation: '#abb2bf',
28
+ Name: '#abb2bf',
29
+ Name.Function: '#61afef',
30
+ Name.Function.Magic: '#61afef',
31
+ Name.Builtin: '#61afef',
32
+ Name.Builtin.Pseudo: '#e06c75',
33
+ Name.Class: '#e5c07b',
34
+ Name.Decorator: '#61afef',
35
+ Name.Namespace: '#e5c07b',
36
+ Name.Tag: '#e06c75',
37
+ Name.Attribute: '#d19a66',
38
+ Name.Constant: '#d19a66',
39
+ String: '#98c379',
40
+ String.Escape: '#56b6c2',
41
+ Number: '#d19a66',
42
+ Error: '#e06c75',
43
+ }
@@ -0,0 +1,40 @@
1
+ """Markdown -> HTML rendering pipeline for post content.
2
+
3
+ ``render_markdown`` returns a :class:`RenderedContent` exposing the rendered
4
+ ``html`` (with the code chrome from :mod:`kioblog.markdown.code_chrome`) and the
5
+ ``toc`` table of contents derived from the ``<h2>`` headings, used for the
6
+ "On this page" index. Also wired as ``MARKDOWNX_MARKDOWNIFY_FUNCTION`` so the
7
+ admin preview matches the public render.
8
+ """
9
+
10
+ import markdown
11
+ from markdown.extensions.toc import TocExtension
12
+
13
+ from kioblog.markdown.code_chrome import CodeChromeExtension
14
+
15
+
16
+ class RenderedContent(str):
17
+ """A rendered HTML string that also carries the generated ``toc``.
18
+
19
+ Subclasses ``str`` so ``MARKDOWNX_MARKDOWNIFY_FUNCTION`` (which expects a
20
+ string) works unchanged, while ``Post.content_html``/``Post.toc`` can read
21
+ the structured attributes.
22
+ """
23
+
24
+ def __new__(cls, html, toc):
25
+ obj = super().__new__(cls, html)
26
+ obj.html = html
27
+ obj.toc = toc
28
+ return obj
29
+
30
+
31
+ def render_markdown(text):
32
+ md = markdown.Markdown(
33
+ extensions=[
34
+ CodeChromeExtension(),
35
+ TocExtension(baselevel=2, permalink=False),
36
+ ],
37
+ output_format='html5',
38
+ )
39
+ html = md.convert(text or '')
40
+ return RenderedContent(html, getattr(md, 'toc', ''))
@@ -0,0 +1,82 @@
1
+ # Generated by Django 4.0.3 on 2022-04-12 18:35
2
+
3
+ from django.conf import settings
4
+ from django.db import migrations, models
5
+ import django.db.models.deletion
6
+
7
+
8
+ class Migration(migrations.Migration):
9
+
10
+ initial = True
11
+
12
+ dependencies = [
13
+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),
14
+ ]
15
+
16
+ operations = [
17
+ migrations.CreateModel(
18
+ name='Category',
19
+ fields=[
20
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
21
+ ('title', models.CharField(max_length=250)),
22
+ ('slug', models.SlugField(max_length=200)),
23
+ ('featured', models.BooleanField(default=False)),
24
+ ],
25
+ options={
26
+ 'verbose_name_plural': 'Categories',
27
+ },
28
+ ),
29
+ migrations.CreateModel(
30
+ name='Meta',
31
+ fields=[
32
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
33
+ ('key', models.CharField(max_length=100)),
34
+ ('value', models.CharField(max_length=250, null=True)),
35
+ ],
36
+ ),
37
+ migrations.CreateModel(
38
+ name='Page',
39
+ fields=[
40
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
41
+ ('title', models.CharField(max_length=50)),
42
+ ('slug', models.SlugField(max_length=200)),
43
+ ('description', models.TextField()),
44
+ ('content', models.TextField()),
45
+ ('created', models.DateField(auto_now_add=True)),
46
+ ('public', models.BooleanField(default=True)),
47
+ ],
48
+ ),
49
+ migrations.CreateModel(
50
+ name='Post',
51
+ fields=[
52
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
53
+ ('title', models.CharField(max_length=250)),
54
+ ('content', models.TextField()),
55
+ ('blocked', models.BooleanField(default=False)),
56
+ ('created', models.DateField(auto_now_add=True)),
57
+ ('slug', models.SlugField(max_length=200)),
58
+ ('image', models.FileField(null=True, upload_to='kioblog')),
59
+ ('draft', models.BooleanField(default=False)),
60
+ ('meta_title', models.CharField(blank=True, max_length=250, null=True)),
61
+ ('meta_description', models.CharField(blank=True, max_length=250, null=True)),
62
+ ('category', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='kioblog.category')),
63
+ ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
64
+ ],
65
+ options={
66
+ 'ordering': ['-id'],
67
+ },
68
+ ),
69
+ migrations.CreateModel(
70
+ name='Comment',
71
+ fields=[
72
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
73
+ ('username', models.CharField(max_length=100)),
74
+ ('content', models.TextField()),
75
+ ('created', models.DateField(auto_now_add=True)),
76
+ ('email', models.EmailField(max_length=254)),
77
+ ('api', models.CharField(blank=True, max_length=50, null=True)),
78
+ ('parent', models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='kioblog.comment')),
79
+ ('post', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='comments', to='kioblog.post')),
80
+ ],
81
+ ),
82
+ ]
@@ -0,0 +1,21 @@
1
+ # Generated by Django 3.2.12 on 2022-07-24 18:36
2
+
3
+ from django.db import migrations
4
+
5
+
6
+ def populate_kioblog_settings(apps, schema_editor):
7
+ setting_model = apps.get_model('kioblog', 'Meta')
8
+ setting_model.objects.get_or_create(key='blog_title', value='Blog Title')
9
+ setting_model.objects.get_or_create(key='meta_description', value='Meta Description')
10
+ setting_model.objects.get_or_create(key='meta_title', value='Meta Title')
11
+
12
+
13
+ class Migration(migrations.Migration):
14
+
15
+ dependencies = [
16
+ ('kioblog', '0001_initial'),
17
+ ]
18
+
19
+ operations = [
20
+ migrations.RunPython(populate_kioblog_settings),
21
+ ]
@@ -0,0 +1,23 @@
1
+ # Generated by Django 3.2.12 on 2022-08-09 17:35
2
+
3
+ from django.db import migrations
4
+
5
+
6
+ def populate_kioblog_settings(apps, schema_editor):
7
+ setting_model = apps.get_model('kioblog', 'Meta')
8
+ setting_model.objects.get_or_create(key='social_twitter', value='https://twitter.com/kioblog')
9
+ setting_model.objects.get_or_create(key='social_facebook', value='https://facebook.com/kioblog')
10
+ setting_model.objects.get_or_create(key='social_instagram', value='https://instagram.com/kioblog')
11
+ setting_model.objects.get_or_create(key='social_youtube', value='https://youtube.com/kioblog')
12
+ setting_model.objects.get_or_create(key='social_twitch', value='https://twitch.com/kioblog')
13
+
14
+
15
+ class Migration(migrations.Migration):
16
+
17
+ dependencies = [
18
+ ('kioblog', '0002_auto_20220724_1836'),
19
+ ]
20
+
21
+ operations = [
22
+ migrations.RunPython(populate_kioblog_settings),
23
+ ]
@@ -0,0 +1,44 @@
1
+ from django.db import migrations, models
2
+ import django.utils.timezone
3
+
4
+
5
+ class Migration(migrations.Migration):
6
+
7
+ dependencies = [
8
+ ('kioblog', '0003_auto_20220809_1735'),
9
+ ]
10
+
11
+ operations = [
12
+ migrations.CreateModel(
13
+ name='Tag',
14
+ fields=[
15
+ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
16
+ ('title', models.CharField(max_length=60)),
17
+ ('slug', models.SlugField(max_length=200, unique=True)),
18
+ ],
19
+ ),
20
+ migrations.AlterModelOptions(
21
+ name='post',
22
+ options={'ordering': ['-published', '-id']},
23
+ ),
24
+ migrations.AddField(
25
+ model_name='post',
26
+ name='excerpt',
27
+ field=models.TextField(blank=True),
28
+ ),
29
+ migrations.AddField(
30
+ model_name='post',
31
+ name='is_featured',
32
+ field=models.BooleanField(default=False),
33
+ ),
34
+ migrations.AddField(
35
+ model_name='post',
36
+ name='published',
37
+ field=models.DateTimeField(default=django.utils.timezone.now),
38
+ ),
39
+ migrations.AddField(
40
+ model_name='post',
41
+ name='tags',
42
+ field=models.ManyToManyField(blank=True, related_name='posts', to='kioblog.Tag'),
43
+ ),
44
+ ]
@@ -0,0 +1,39 @@
1
+ """Backfill Post.published from the legacy Post.created date.
2
+
3
+ Existing rows got published=timezone.now() when the field was added in 0004;
4
+ this copies their real created date (at midnight, timezone-aware) so ordering
5
+ and prev/next reflect the original publish order. New rows keep the default.
6
+ """
7
+
8
+ import datetime
9
+
10
+ from django.db import migrations
11
+ from django.utils import timezone
12
+
13
+
14
+ def backfill_published(apps, schema_editor):
15
+ Post = apps.get_model('kioblog', 'Post')
16
+ for post in Post.objects.all():
17
+ if not post.created:
18
+ continue
19
+ dt = datetime.datetime.combine(post.created, datetime.time.min)
20
+ if settings_use_tz() and timezone.is_naive(dt):
21
+ dt = timezone.make_aware(dt, timezone.get_default_timezone())
22
+ post.published = dt
23
+ post.save(update_fields=['published'])
24
+
25
+
26
+ def settings_use_tz():
27
+ from django.conf import settings
28
+ return getattr(settings, 'USE_TZ', False)
29
+
30
+
31
+ class Migration(migrations.Migration):
32
+
33
+ dependencies = [
34
+ ('kioblog', '0004_tag_post_fields'),
35
+ ]
36
+
37
+ operations = [
38
+ migrations.RunPython(backfill_published, migrations.RunPython.noop),
39
+ ]
@@ -0,0 +1,17 @@
1
+ from django.db import migrations
2
+ import markdownx.models
3
+
4
+
5
+ class Migration(migrations.Migration):
6
+
7
+ dependencies = [
8
+ ('kioblog', '0005_backfill_published'),
9
+ ]
10
+
11
+ operations = [
12
+ migrations.AlterField(
13
+ model_name='post',
14
+ name='content',
15
+ field=markdownx.models.MarkdownxField(),
16
+ ),
17
+ ]
File without changes
kioblog/models.py ADDED
@@ -0,0 +1,135 @@
1
+ import re
2
+ from html import unescape
3
+
4
+ from django.db import models
5
+ from django.conf import settings
6
+ from django.utils import timezone
7
+
8
+ from markdownx.models import MarkdownxField
9
+
10
+ from kioblog.markdown.render import render_markdown
11
+
12
+
13
+ class Category(models.Model):
14
+ title = models.CharField(max_length=250)
15
+ slug = models.SlugField(max_length=200)
16
+ featured = models.BooleanField(default=False)
17
+
18
+ def __str__(self):
19
+ return self.title
20
+
21
+ def post_count(self):
22
+ return self.post_set.filter(draft=False).count()
23
+
24
+ class Meta:
25
+ verbose_name_plural = "Categories"
26
+
27
+
28
+ class Tag(models.Model):
29
+ title = models.CharField(max_length=60)
30
+ slug = models.SlugField(max_length=200, unique=True)
31
+
32
+ def __str__(self):
33
+ return self.title
34
+
35
+
36
+ class Post(models.Model):
37
+ title = models.CharField(max_length=250)
38
+ content = MarkdownxField()
39
+ user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
40
+ blocked = models.BooleanField(default=False)
41
+ category = models.ForeignKey(Category, on_delete=models.CASCADE)
42
+ created = models.DateField(auto_now_add=True)
43
+ published = models.DateTimeField(default=timezone.now)
44
+ slug = models.SlugField(max_length=200)
45
+ image = models.FileField(upload_to=settings.UPLOAD_TO, null=True)
46
+ draft = models.BooleanField(default=False)
47
+ tags = models.ManyToManyField(Tag, blank=True, related_name='posts')
48
+ excerpt = models.TextField(blank=True)
49
+ is_featured = models.BooleanField(default=False)
50
+ meta_title = models.CharField(null=True, blank=True, max_length=250)
51
+ meta_description = models.CharField(null=True, blank=True, max_length=250)
52
+
53
+ def __str__(self):
54
+ return self.title
55
+
56
+ class Meta:
57
+ ordering = ['-published', '-id']
58
+
59
+ def _render(self):
60
+ if not hasattr(self, '_rendered'):
61
+ self._rendered = render_markdown(self.content)
62
+ return self._rendered
63
+
64
+ @property
65
+ def content_html(self):
66
+ return self._render().html
67
+
68
+ @property
69
+ def toc(self):
70
+ return self._render().toc
71
+
72
+ @property
73
+ def reading_time(self):
74
+ words = len(re.sub(r'<[^>]+>', '', self.content_html).split())
75
+ return max(1, round(words / 200))
76
+
77
+ def first_paragraph(self):
78
+ re_pattern = re.compile(r'(<p.*?</p>)')
79
+ paragraphs = re_pattern.search(self.content)
80
+ if not paragraphs:
81
+ return ''
82
+ return paragraphs.groups()[0]
83
+
84
+ @property
85
+ def display_excerpt(self):
86
+ if self.excerpt:
87
+ return self.excerpt
88
+ match = re.search(r'<p[^>]*>(.*?)</p>', self.content_html, re.DOTALL)
89
+ if not match:
90
+ return ''
91
+ text = re.sub(r'<[^>]+>', '', match.group(1)).strip()
92
+ return unescape(text)
93
+
94
+ def get_previous(self):
95
+ tie_break = models.Q(published__lt=self.published) | models.Q(published=self.published, id__lt=self.id)
96
+ return Post.objects.filter(draft=False).filter(tie_break).order_by('-published', '-id').first()
97
+
98
+ def get_next(self):
99
+ tie_break = models.Q(published__gt=self.published) | models.Q(published=self.published, id__gt=self.id)
100
+ return Post.objects.filter(draft=False).filter(tie_break).order_by('published', 'id').first()
101
+
102
+ def related_posts(self, limit=4):
103
+ qs = (Post.objects.filter(draft=False)
104
+ .exclude(pk=self.pk)
105
+ .filter(models.Q(category=self.category) | models.Q(tags__in=self.tags.all()))
106
+ .distinct())
107
+ return qs[:limit]
108
+
109
+ @staticmethod
110
+ def get_recent_posts(current_slug=None):
111
+ recent_posts = Post.objects.filter(draft=False)
112
+ if current_slug is not None:
113
+ recent_posts = recent_posts.exclude(slug=current_slug)
114
+ return recent_posts[:5]
115
+
116
+
117
+ class Comment(models.Model):
118
+ username = models.CharField(max_length=100)
119
+ content = models.TextField()
120
+ parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True)
121
+ post = models.ForeignKey(Post, related_name='comments', on_delete=models.CASCADE)
122
+ created = models.DateField(auto_now_add=True)
123
+ email = models.EmailField()
124
+ api = models.CharField(null=True, blank=True, max_length=50)
125
+
126
+ def __str__(self):
127
+ return '{} - {}'.format(self.username, self.post)
128
+
129
+
130
+ class Meta(models.Model):
131
+ key = models.CharField(max_length=100)
132
+ value = models.CharField(max_length=250, null=True)
133
+
134
+ def __str__(self):
135
+ return self.key