【Django 实验三】个人主页开发实战
【Django 实验三】个人主页开发实战作者刘静怡 | 学号F23016208 | 完成日期2026年3月29日目录环境准备项目创建数据模型设计视图函数编写模板系统Admin 后台配置页面美化功能完善总结一、环境准备1.1 环境要求Python: 3.10Django: 5.2 LTS数据库: MySQL 8.0Pillow: 图片处理库django-simpleui: Admin 后台美化1.2 安装依赖# 安装 Django 和相关依赖pip install Django5.2.*pip install Pillow pip install django-simpleui pip install pymysql1.3 数据库配置使用 phpstudy_pro 配置 MySQL 数据库配置项值主机127.0.0.1端口3306用户名root密码root数据库名exp3_homepage创建数据库CREATEDATABASEexp3_homepageCHARACTERSETutf8mb4COLLATEutf8mb4_unicode_ci;二、项目创建2.1 创建 Django 项目和应用# 1. 创建 Django 项目django-admin startproject mysite# 2. 创建 profiles 应用python manage.py startapp profiles2.2 项目目录结构exp3_homepage/ ├── manage.py # Django 管理脚本 ├── mysite/ # 项目配置目录 │ ├── __init__.py # pymysql 配置 │ ├── settings.py # 项目配置 │ ├── urls.py # 主 URL 配置 │ └── wsgi.py # WSGI 配置 ├── profiles/ # 个人主页应用 │ ├── __init__.py │ ├── admin.py # Admin 配置 │ ├── apps.py # 应用配置 │ ├── models.py # 数据模型 │ ├── views.py # 视图函数 │ ├── urls.py # URL 配置 │ └── migrations/ # 数据库迁移 ├── templates/ # 模板目录 │ └── profiles/ │ └── index.html # 个人主页模板 ├── media/ # 用户上传文件目录 │ └── avatars/ # 头像存储目录 └── static/ # 静态文件目录2.3 settings.py 配置importos INSTALLED_APPS[django.contrib.admin,django.contrib.auth,django.contrib.contenttypes,django.contrib.sessions,django.contrib.messages,django.contrib.staticfiles,simpleui,profiles,]DATABASES{default:{ENGINE:django.db.backends.mysql,NAME:exp3_homepage,USER:root,PASSWORD:root,HOST:127.0.0.1,PORT:3306,OPTIONS:{charset:utf8mb4,},}}LANGUAGE_CODEzh-hansTIME_ZONEAsia/ShanghaiUSE_TZTrueMEDIA_URL/media/MEDIA_ROOTos.path.join(BASE_DIR,media)SIMPLEUI_HOME_TITLE刘静怡 - 个人主页管理三、数据模型设计3.1 Profile 模型定义在profiles/models.py中定义个人资料模型fromdjango.dbimportmodelsclassProfile(models.Model):个人资料模型namemodels.CharField(姓名,max_length50,default刘静怡)gendermodels.CharField(性别,max_length10,default女)student_idmodels.CharField(学号,max_length20,defaultF23016208)birth_datemodels.DateField(出生日期,blankTrue,nullTrue)hometownmodels.CharField(籍贯,max_length100,blankTrue)emailmodels.EmailField(邮箱,blankTrue)phonemodels.CharField(电话,max_length20,blankTrue)avatarmodels.ImageField(头像,upload_toavatars/,blankTrue,nullTrue)biomodels.TextField(个人简介,blankTrue)researchmodels.TextField(研究方向,blankTrue)projectsmodels.TextField(项目经验,blankTrue)created_atmodels.DateTimeField(创建时间,auto_now_addTrue)updated_atmodels.DateTimeField(更新时间,auto_nowTrue)classMeta:verbose_name个人资料verbose_name_plural个人资料ordering[-updated_at]def__str__(self):returnself.name3.2 模型字段说明字段类型说明默认值nameCharField(50)姓名刘静怡genderCharField(10)性别女student_idCharField(20)学号F23016208birth_dateDateField出生日期nullhometownCharField(100)籍贯空emailEmailField邮箱空phoneCharField(20)电话空avatarImageField头像nullbioTextField个人简介空researchTextField研究方向空projectsTextField项目经验空created_atDateTimeField创建时间自动updated_atDateTimeField更新时间自动3.3 字段类型详解CharField: 字符串字段需要指定max_lengthTextField: 文本字段无最大长度限制EmailField: 邮箱字段带格式验证DateField: 日期字段ImageField: 图片字段需要 Pillow 支持DateTimeField: 日期时间字段auto_now_add自动添加创建时间3.4 执行数据库迁移# 1. 创建迁移文件python manage.py makemigrations# 2. 执行迁移python manage.py migrate四、视图函数编写4.1 个人主页视图在profiles/views.py中编写视图函数fromdjango.shortcutsimportrenderfrom.modelsimportProfiledefindex(request): 个人主页视图 显示用户个人资料信息 profileProfile.objects.first()ifnotprofile:profileProfile.objects.create(name刘静怡,gender女,student_idF23016208,bio暂无简介,research暂无研究方向,projects暂无项目经验)context{profile:profile,}returnrender(request,profiles/index.html,context)4.2 视图函数说明defindex(request): 个人主页视图函数 参数: request: Django HttpRequest 对象 返回: HttpResponse: 渲染后的 HTML 页面 处理流程: 1. 从数据库获取第一个 Profile 对象 2. 如果不存在自动创建一个默认 Profile 3. 将 profile 对象传递给模板 4. 渲染并返回 HTML 页面 4.3 URL 路由配置profiles/urls.pyfromdjango.urlsimportpathfrom.importviews app_nameprofilesurlpatterns[path(,views.index,nameindex),]mysite/urls.pyfromdjango.contribimportadminfromdjango.urlsimportpathfromdjango.confimportsettingsfromdjango.conf.urls.staticimportstaticfromprofilesimportviews urlpatterns[path(admin/,admin.site.urls),path(,views.index,namehome),]ifsettings.DEBUG:urlpatternsstatic(settings.MEDIA_URL,document_rootsettings.MEDIA_ROOT)五、模板系统5.1 模板文件结构templates/ └── profiles/ └── index.html # 个人主页模板5.2 个人主页模板templates/profiles/index.html!DOCTYPEhtmlhtmllangzh-CNheadmetacharsetUTF-8metanameviewportcontentwidthdevice-width, initial-scale1.0title刘静怡 - 个人主页/titlelinkhrefhttps://cdn.jsdelivr.net/npm/bootstrap5.3.0/dist/css/bootstrap.min.cssrelstylesheetstylebody{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);min-height:100vh;padding:20px 0;}.profile-card{background:white;border-radius:20px;box-shadow:0 20px 60pxrgba(0,0,0,0.3);overflow:hidden;max-width:1000px;margin:0 auto;}/* 更多样式... *//style/headbodydivclasscontainerdivclassprofile-carddivclassprofile-headerh1个人主页/h1/divdivclassprofile-bodydivclassprofile-left{% if profile.avatar %}imgsrc{{ profile.avatar.url }}alt{{ profile.name }}classavatar{% else %}divclassavatar-placeholder{{ profile.name|slice::1 }}/div{% endif %}h2classmt-3{{ profile.name }}/h2pclasstext-muted{{ profile.gender }} | {{ profile.student_id }}/p/divdivclassprofile-right!-- 详细信息 --/div/div/div/div/body/html5.3 Django 模板语法!-- 变量渲染 --{{ profile.name }}!-- 条件判断 --{% if profile.avatar %}imgsrc{{ profile.avatar.url }}{% else %}divclassplaceholder无头像/div{% endif %}!-- 过滤器 --{{ profile.name|slice::1 }}!-- 取第一个字符 --!-- URL 反向解析 --ahref{% url profile %}个人主页/a5.4 模板变量说明变量说明profile.name姓名profile.gender性别profile.student_id学号profile.birth_date出生日期profile.hometown籍贯profile.email邮箱profile.phone电话profile.avatar头像图片profile.avatar.url头像 URLprofile.bio个人简介profile.research研究方向profile.projects项目经验六、Admin 后台配置6.1 创建超级用户python manage.py createsuperuser# 用户名: admin# 密码: admin1236.2 Admin 配置在profiles/admin.py中配置后台管理fromdjango.contribimportadminfrom.modelsimportProfileadmin.register(Profile)classProfileAdmin(admin.ModelAdmin):个人资料后台管理# 列表页显示的列list_display[name,gender,student_id,email,phone,created_at]# 右侧过滤栏list_filter[gender,created_at]# 搜索框search_fields[name,student_id,email,hometown]# 默认排序ordering[-updated_at]# 表单字段分组fieldsets((基本信息,{fields:(name,gender,student_id,avatar)}),(详细信息,{fields:(birth_date,hometown,email,phone)}),(个人描述,{fields:(bio,research,projects)}),)# 只读字段readonly_fields[created_at,updated_at]6.3 Admin 配置选项详解选项说明list_display列表页显示的字段list_filter右侧过滤栏字段search_fields搜索框搜索字段ordering默认排序方式fieldsets表单字段分组readonly_fields只读字段6.4 访问 Admin 后台http://127.0.0.1:8000/admin/七、页面美化7.1 页面布局设计采用左右分栏布局┌─────────────────────────────────────────────────────────┐ │ 个人主页 │ ├───────────────────────────┬─────────────────────────────┤ │ │ │ │ [头像占位符] │ 详细信息 │ │ │ │ │ 刘静怡 │ 出生日期 | 籍贯 │ │ 女 | F23016208 │ 邮箱 | 电话 │ │ │ │ │ │ 个人简介 │ │ │ 研究方向 │ │ │ 项目经验 │ │ │ │ └───────────────────────────┴─────────────────────────────┘7.2 Bootstrap 5 使用引入 Bootstrap 5 CDNlinkhrefhttps://cdn.jsdelivr.net/npm/bootstrap5.3.0/dist/css/bootstrap.min.cssrelstylesheetscriptsrchttps://cdn.jsdelivr.net/npm/bootstrap5.3.0/dist/js/bootstrap.bundle.min.js/script7.3 响应式设计media(max-width:768px){.profile-body{flex-direction:column;}.profile-left{border-right:none;border-bottom:1px solid #dee2e6;}}7.4 渐变背景body{background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);min-height:100vh;}八、功能完善8.1 自动创建默认资料在视图函数中添加自动创建逻辑defindex(request):profileProfile.objects.first()ifnotprofile:profileProfile.objects.create(name刘静怡,gender女,student_idF23016208,bio暂无简介,research暂无研究方向,projects暂无项目经验)context{profile:profile}returnrender(request,profiles/index.html,context)8.2 头像上传功能ImageField 配置avatarmodels.ImageField(头像,upload_toavatars/,blankTrue,nullTrue)模板中的头像显示{% if profile.avatar %}imgsrc{{ profile.avatar.url }}classavatar{% else %}divclassavatar-placeholder{{ profile.name|slice::1 }}/div{% endif %}8.3 媒体文件配置settings.pyMEDIA_URL/media/MEDIA_ROOTBASE_DIR/mediaurls.pyfromdjango.conf.urls.staticimportstaticifsettings.DEBUG:urlpatternsstatic(settings.MEDIA_URL,document_rootsettings.MEDIA_ROOT)项目截图查看参考资源Django 官方文档https://docs.djangoproject.com/zh-hans/Bootstrap 5 文档https://getbootstrap.com/docs/5.3/SimpleUI 项目https://gitee.com/tompeppa/simpleui
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2465030.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!