add markdown

This commit is contained in:
2025-07-26 20:27:37 +08:00
parent 67bc42e862
commit 7bcc6460c4
6 changed files with 41 additions and 14 deletions

View File

@@ -1,6 +1,24 @@
from django.contrib import admin
from .models import Post
from django.db import models
from martor.widgets import AdminMartorWidget
# Register your models here.
admin.site.register(Post)
class PostAdmin(admin.ModelAdmin):
# 使用Martor Markdown编辑器替换默认的Textarea
formfield_overrides = {
models.TextField: {'widget': AdminMartorWidget},
}
# 设置列表显示字段
list_display = ('title', 'publish_date', 'created_at')
# 设置搜索字段
search_fields = ('title', 'content')
# 设置日期层级过滤器
date_hierarchy = 'publish_date'
# 设置可编辑字段
list_editable = ('publish_date',)
# 注册自定义的PostAdmin
admin.site.register(Post, PostAdmin)

View File

@@ -1,5 +1,7 @@
from django.db import models
from django.utils import timezone
import markdown
from django.utils.safestring import mark_safe
# Create your models here.
@@ -13,3 +15,6 @@ class Post(models.Model):
def __str__(self):
return f"{self.title} ({self.publish_date.strftime('%Y-%m-%d')})"
def get_markdown_content(self):
return mark_safe(markdown.markdown(self.content))

View File

@@ -6,16 +6,16 @@
</head>
<body>
<!-- 添加样式使整个页面内容居中显示 -->
<div style="max-width: 800px; margin: 0 auto; padding: 0 20px; text-align: center;">
<!-- 添加网站标题 -->
<h1>{{ post.title }}</h1>
<p>{{ post.publish_date }}</p>
<div>{{ post.content|linebreaks }}</div>
<p><a href="/">← 返回首页</a></p>
<div style="max-width: 800px; margin: 0 auto; padding: 0 20px;">
<h1 style="text-align: center;">{{ post.title }}</h1>
<p>发布时间:{{ post.publish_date|date:"Y年n月j日 H:i" }}</p>
<!-- 使用get_markdown_content方法渲染Markdown内容 -->
<div>{{ post.get_markdown_content|safe }}</div>
<br>
<a href="{% url 'index' %}">返回首页</a>
</div>
<footer style="position: fixed; bottom: 0; width: 100%; text-align: center; font-size: 12px; color: #999; background-color: white; padding: 5px 0;">
<a href="https://beian.miit.gov.cn/" target="_blank">闽ICP备2023010767号-2</a>
</footer>
</body>
</html>

View File

@@ -5,7 +5,7 @@ from .models import Post
# Create your views here.
def index(request):
posts = Post.objects.order_by('-created_at')
posts = Post.objects.order_by('created_at')
return render(request, 'blog/index.html', {'posts': posts})

View File

@@ -35,8 +35,8 @@ INSTALLED_APPS = [
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog'
'blog',
'martor',
]
MIDDLEWARE = [

View File

@@ -17,7 +17,11 @@ Including another URLconf
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
# 添加martor的URL配置以支持Markdown编辑器
path('martor/', include('martor.urls')),
# 包含blog应用的URL
path('', include('blog.urls')),
]