基于Python和Django如何搭建个人博客系统?
无聊时候断断续续写的个人博客程序.现在已经基本成型了.登录,注册,评论等功能已经基本都有了.
Github 地址: https://github.com/liangliangyy/DjangoBlog
线上地址: https://www.lylinux.net/
欢迎大家 star.提 pr.这个博客程序是边翻文档边写的.有的地方还不是很完善.欢迎大家指正.
基于Python和Django如何搭建个人博客系统?
楼主登陆界面咋那么像 wordpress !!!!
要基于Python和Django搭建个人博客,核心是创建文章模型、视图和模板。下面是一个最精简的实现方案。
首先,确保已安装Django:pip install django,然后创建项目和应用。
1. 定义模型(models.py) 这是核心,用于存储博客文章。
# blog/models.py
from django.db import models
from django.utils import timezone
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
运行 python manage.py makemigrations 和 python manage.py migrate 来创建数据库表。
2. 创建视图(views.py) 处理请求并返回文章列表和详情。
# blog/views.py
from django.shortcuts import render, get_object_or_404
from .models import Post
def post_list(request):
posts = Post.objects.filter(published_date__isnull=False).order_by('-published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
3. 配置URL(urls.py) 将URL映射到对应的视图。
# blog/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.post_list, name='post_list'),
path('post/<int:pk>/', views.post_detail, name='post_detail'),
]
别忘了在项目的主 urls.py 中包含这个应用的URL配置。
4. 编写模板(HTML文件)
创建 templates/blog/ 目录,然后写两个模板文件。
post_list.html用于显示所有文章列表。post_detail.html用于显示单篇文章详情。
一个简单的 post_list.html 示例:
<h1>博客文章</h1>
{% for post in posts %}
<article>
<h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2>
<p>发布时间: {{ post.published_date }}</p>
<p>{{ post.content|truncatechars:200 }}</p>
</article>
{% endfor %}
5. 创建超级用户和管理后台
运行 python manage.py createsuperuser,然后在 admin.py 中注册模型:
# blog/admin.py
from django.contrib import admin
from .models import Post
admin.site.register(Post)
现在你就可以通过 /admin 后台来发布和管理文章了。
最后,运行 python manage.py runserver,你的基础博客系统就起来了。这只是一个骨架,你可以在此基础上添加分类、标签、评论等功能。
总结:先跑通MVC(模型-视图-模板)这个基础流程。
明明是 Google
哈哈哈是的.登录界面是模仿 Google 的.然后前端是模仿 wordpress 的主题的
登录…
嗯嗯 还是有 bug.我也发现了.周末修掉~~
哈哈,登陆页面不错,档次一下就提高了
哈哈 是也乎 是也乎.
登陆->登录
嗯哼 感谢指正~~
好慢, 15s 才打开。。。
嗯嗯 linode 东京 2 机房.有些地区可能会很慢…
need help …
应该把评论换成 disqus ,现在的太丑了
嗯嗯是的.国内还要备案.烦得要死.坚决抵制!
看了下代码,写得不错,默默 FORK 来学习
嗯嗯 当时就是想着自己实现所有的功能.但是毕竟前端渣…评论界面这块是要改下呢~~
不过打算实现下第三方登录的.oauth 的功能.这样只留一个留言框会好点儿~~
哈哈 感谢大家的测试.收到三四封异常邮件了周末一并修掉~
前端也都自己写吗?
不是的哈.前端是模仿 wordpress 的主题的哈
create an account 还是 sign in
还有登录和登陆
嗯嗯 感谢.周末改掉~~
评论直接用多说吧,本来也想自己开发的,但是越了解感觉坑越大。。还是暂且放弃了
就是因为多说垃圾评论太多了然后才弃用的~~
hhh, 好吧。。过段时间我也试试加上评论模块
大家不要只收藏帖子呀点点 star 点点 fork 也是阔以滴
后面会继续完善滴~~
大家都是怎么用缓存的,类似这样的博客大家有没有什么缓存使用的经验或者想法意见呀,现在缓存这儿有点不确定改怎么用。
老哥,看了你的博客速度好快。还是 hexo+coding 托管吗
是的,说白了 coding 的 CDN 好。。


