探索GitHub顶级项目:Django在macOS Ventura平台的实战应用

云信安装大师
90
AI 质量分
10 5 月, 2025
4 分钟阅读
0 阅读

探索GitHub顶级项目:Django在macOS Ventura平台的实战应用

引言

Django作为GitHub上最受欢迎的Python Web框架之一,以其”开箱即用”的特性深受开发者喜爱。本文将带你在macOS Ventura系统上从零开始搭建Django开发环境,并通过一个完整的博客项目示例,展示Django的核心功能。

准备工作

环境要求

  • macOS Ventura (13.0或更高版本)
  • 终端访问权限
  • 稳定的网络连接

前置知识

  • 基础Python语法
  • 基本命令行操作

第一步:安装Python和虚拟环境

虽然macOS预装了Python,但建议使用Homebrew安装最新版本:

代码片段
# 1. 安装Homebrew(如果尚未安装)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# 2. 安装Python最新稳定版
brew install python

# 3. 验证安装
python3 --version
pip3 --version

# 4. 创建虚拟环境(推荐)
python3 -m venv django_env
source django_env/bin/activate

原理说明
– 虚拟环境可以隔离项目依赖,避免不同项目间的包冲突
source命令激活环境后,所有Python包将安装在当前环境中

第二步:安装Django并创建项目

代码片段
# 1. 安装Django最新稳定版
pip install django

# 2. 创建新项目(这里创建名为myblog的项目)
django-admin startproject myblog

# 3. 进入项目目录
cd myblog

# 4. 启动开发服务器验证安装
python manage.py runserver

访问 http://127.0.0.1:8000 ,你应该能看到Django的欢迎页面。

注意事项
– Django默认使用SQLite数据库,适合开发和测试环境
runserver命令启动的是开发服务器,不要在生产环境中使用

第三步:创建博客应用

代码片段
# 在项目目录下执行(确保已激活虚拟环境)
python manage.py startapp blog

然后修改myblog/settings.py文件,添加新应用:

代码片段
INSTALLED_APPS = [
    ...
    'blog.apps.BlogConfig', # 添加这行
]

文件结构说明

代码片段
myblog/
    ├── manage.py         # Django命令行工具
    ├── myblog/
    │   ├── __init__.py   
    │   ├── settings.py   # 项目配置
    │   ├── urls.py       # URL路由配置
    │   └── wsgi.py       # WSGI配置(生产部署用)
    └── blog/             # 我们的博客应用
        ├── migrations/   # 数据库迁移文件
        ├── __init__.py   
        ├── admin.py      # Admin后台配置  
        ├── apps.py       
        ├── models.py     # 数据模型定义  
        ├── tests.py      
        └── views.py      # 视图函数定义  

第四步:定义博客数据模型

编辑blog/models.py文件:

代码片段
from django.db import models
from django.contrib.auth.models import User

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.title

class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE)
    author = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return f"Comment by {self.author} on {self.post.title}"

模型字段解释
CharField: 用于存储短文本(如标题)
TextField: 用于存储长文本内容(如文章正文)
ForeignKey: 建立一对多关系(如文章与作者、评论与文章)
auto_now_add: 只在创建时自动设置当前时间
auto_now:每次保存时自动更新为当前时间

第五步:迁移数据库并创建超级用户

代码片段
#1.生成迁移文件 
python manage.py makemigrations 

#2.执行迁移 
python manage.py migrate 

#3.创建管理员账户 
python manage.py createsuperuser 

按照提示输入用户名、邮箱和密码。这个账户将用于访问Django管理后台。

第六步:注册模型到Admin后台

编辑blog/admin.py:

代码片段
from django.contrib import admin 
from .models import Post, Comment 

class CommentInline(admin.TabularInline): 
model = Comment 
extra=1 

class PostAdmin(admin.ModelAdmin): 
inlines=[CommentInline] 

admin.site.register(Post,PostAdmin) 
admin.site.register(Comment) 

启动开发服务器并访问http://127.0.0.1:8000/admin:

代码片段
python manage.py runserver 

实践经验
-Django的Admin后台非常适合快速构建内容管理系统(CMS)
-TabularInline允许我们在文章编辑页面直接管理关联的评论

第七步:创建视图和URL路由

首先编辑blog/views.py:

代码片段
from django.shortcuts import render,get_object_or_404 
from .models import Post 

def post_list(request): 
posts=Post.objects.all().order_by('-created_at') 
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}) 

然后创建URL路由。先在blog目录下新建urls.py:

代码片段
from django.urls import path 
from .import views 

urlpatterns=[ 
path('',views.post_list,name='post_list'),  
path('<int:pk>/',views.post_detail,name='post_detail'),  
]  

接着修改项目的myblog/urls.py:

代码片段
from django.contrib import admin  
from django.urls import path,include  

urlpatterns=[  
path('admin/',admin.site.urls),  
path('',include('blog.urls')),  
]  

第八步:创建模板

blog目录下新建templates/blog/文件夹,然后创建两个HTML模板文件:

  1. post_list.html:
代码片段
<!DOCTYPE html>  
<html>  
<head>  
<title>My Blog</title>  
</head>  
<body>  
<h1>Blog Posts</h1>  

<ul>  
{%for post in posts%}  
<li><a href="{{post.id}}">{{post.title}}</a>-{{post.author.username}}</li>  
{%endfor%}  
</ul>  

<a href="/admin">Admin Panel</a>  

</body>  
</html>   
  1. post_detail.html:
代码片段
<!DOCTYPE html>   
<html>   
<head>   
<title>{{post.title}}</title>   
</head>   
<body>   

<h1>{{post.title}}</h1>   
<p><em>{{post.created_at}} by {{post.author.username}}</em></p>   

<div>{{post.content|linebreaks}}</div>

<h2>Comments:</h2>
{%if post.comment_set.all%}
<ul>
{%for comment in post.comment_set.all%}
<li>{{comment.content}}<br>
<small>{{comment.author}} at {{comment.created_at}}</small>
</li>
{%endfor%}
</ul>
{%else%}
<p>No comments yet.</p>
{%endif%}

<a href="/">Back to list</a>

</body>
</html>

模板语法说明:
{% %}: Django模板标签,用于逻辑控制
{{ }}:变量输出
|linebreaks:过滤器,将换行符转换为HTML的<br>

第九步:测试完整流程

1.访问http://127.0.0.1:8000/admin并登录
2.添加几篇博客文章和一些评论
3.访问http://127.0.0.1:8000查看文章列表
4点击文章标题查看详情页

常见问题解决

问题1:端口被占用

解决方案:

代码片段
#指定其他端口(如8001)    
python manage.py runserver8001     

问题2:静态文件不显示

解决方案:

在settings.py中添加:

代码片段
STATIC_URL='/static/'    
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')]     

然后在项目根目录下创建static文件夹存放CSS、JS等静态资源。

问题3:Django版本冲突

解决方案:

检查当前Django版本并指定安装特定版本:

代码片段
pip show django     
pip install django==4.x.x     

总结

通过本教程我们完成了以下工作:

✅在macOSVentura上搭建了Django开发环境
✅创建了一个完整的博客应用
✅实现了文章和评论的数据模型
✅配置了DjangoAdmin后台管理界面
✅构建了基本的视图和URL路由
✅设计了前端模板展示内容

作为扩展你可以尝试添加以下功能:

•用户认证系统(注册/登录)
•Markdown编辑器支持
•图片上传功能
•RESTAPI接口(使用DRF)

GitHub上有许多优秀的Django项目值得学习比如:

djangoproject/djangoDjango官方仓库
wsvincent/awesome-djangoDjango资源集合

希望本教程能帮助你顺利开启Django开发之旅!

原创 高质量