Files
blog/myblog/blog/models.py

71 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from django.conf import settings
from django.db import models
from django.utils import timezone
import markdown
from django.utils.safestring import mark_safe
from mdeditor.fields import MDTextField
class Post(models.Model):
title = models.CharField(max_length=100)
content = MDTextField() # ✅ 改成这里
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
publish_date = models.DateTimeField(default=timezone.now)
def __str__(self):
return f"{self.title} ({self.publish_date.strftime('%Y-%m-%d')})"
def get_markdown_content(self):
import re
import emoji
content = self.content
media_url = settings.MEDIA_URL.rstrip('/')
# 统一处理所有可能的图片路径格式
# 处理Markdown格式的图片 ![alt](path)
def replace_md_image(match):
alt_text = match.group(1)
img_path = match.group(2)
# 如果路径已经包含媒体URL则不处理
if img_path.startswith(media_url):
return match.group(0)
# 如果是相对路径则添加媒体URL前缀
if not img_path.startswith(('http://', 'https://', '/')):
return f'![{alt_text}]({media_url}/{img_path})'
return match.group(0)
# 处理HTML格式的图片 <img src="path">
def replace_html_image(match):
quote = match.group(1) or ''
img_path = match.group(2)
# 如果路径已经包含媒体URL则不处理
if img_path.startswith(media_url):
return match.group(0)
# 如果是相对路径则添加媒体URL前缀
if not img_path.startswith(('http://', 'https://', '/')):
return f'src="{media_url}/{img_path}"'
return match.group(0)
# 使用函数替换处理所有Markdown图片
content = re.sub(
r'!\[([^\]]*)\]\(([^)]+)\)',
replace_md_image,
content
)
# 使用函数替换处理所有HTML图片
content = re.sub(
r'src=(["\']?)([^"\'>\s]+)\1',
replace_html_image,
content
)
# 先转换markdown到HTML
html_content = markdown.markdown(content)
# 将emoji shortcode转换为实际的emoji字符
html_content = emoji.emojize(html_content, language='alias')
return mark_safe(html_content)