diff --git a/blog/posts/views.py b/blog/posts/views.py index 8f51fc8..406f9a4 100644 --- a/blog/posts/views.py +++ b/blog/posts/views.py @@ -1,12 +1,13 @@ from django.shortcuts import render, get_object_or_404 from django.http import HttpResponse - +from django.db.models.query import QuerySet from .models import Post from comments.models import Comment from comments import services as comments_services import re +from re import Match def index(request): @@ -15,6 +16,20 @@ def index(request): return render(request, "posts/index.html", {"posts": post_list}) +def image_processing(match: Match, images: QuerySet) -> str: + """Заменяет строку с шорткодом [[image:slug]] на валидный HTML тег. + Из match берется slug картинки, по которому потом выбираем из + images ее url. Если объекта с таким slug нет (IndexError), то заменяем шорткод + картинки на пустую строку.""" + sl = match.group(1) + try: + url = images.filter(slug=sl)[0].image.url + replacement = f"
" + except IndexError: + replacement = "" + return replacement + + def detail(request, post_id): """Страница с просмотром поста.""" # вынести отсюда все. Также надо обработать текст поста тут. @@ -30,7 +45,7 @@ def detail(request, post_id): # вывод картинок в посте, замена шаблона по регулярке post.text = re.sub( r"\[\[image\:(.+?)\]\]", - lambda x: f"", + lambda x: image_processing(x, images), post.text, )