月月芽头像
Django 博客系统项目实战详细图文教程 1--博客系统前端后环境搭建封面图

Django 博客系统项目实战详细图文教程 1--博客系统前端后环境搭建

来源引用网络知识与某站曹老师视频相互结合学习记录,仅供参考!

博客系统项目架构搭建

一、后端架构搭建

创建项目

1、PyCharm 工具→文件(F)→新建项目...→选中“Django”项目→自定义输入名称后单击“创建”按钮,建议使用项目虚拟环境,虚拟环境可以为每个项目创建一个独立的 Python 运行环境,确保使用的第三方库版本与其他项目不同,从而避免依赖包版本冲突;

2、打开“cokeblog”项目,通过 PyCharm 工具→工具(T)→运行 manage.py 任务...(Ctrl+Alt+R)→打开 Django 内置工具来创建子模块;这里根据实际项目需求来创建 5 个子模块;

# user用户模块
startapp user

# album相册模块
startapp album

# link友情链接模块
startapp link

# message留言模块
startapp message

# article博客帖子模块
startapp article

添加配置项

3、现在使用 Django 内置工具来创建子模块后会自动生成并添加对应的子模块配置信息,如若没有烦请自行手动添加;

请求分发

4、为了统一管理请求分发,需要在模块项目中分别创建 urls 映射,在“user用户、album相册、link友情链接、message留言、article博客帖子”子模块下新建名称为“urls.py”的 Python 文件;

5、修改项目“cokeblog”应用下的“urls.py”文件中的映射关系,填写完成后建议先注释一下,因为其他子模块中的“urls.py”文件现在都是空的,此时若运行项目则会报错,得至少有一个请求;

"""
URL configuration for cokeblog project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/6.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include

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

    # 导包引入from django.urls import include
    # 表示前端用户请求是“某某”开头的话会全部分发到对应的模块中,具体的请求再去对应的子模块里去匹配处理
    # path('user/', include('user.urls')),            # 用户模块
    # path('album/', include('album.urls')),          # 相册模块
    # path('link/', include('link.urls')),            # 友情链接模块
    # path('message/', include('message.urls')),      # 留言模块
    # path('article/', include('article.urls'))       # 帖子模块
]

设置 Admin 后台系统支持中文配置

6、修改项目“cokeblog”应用下的“settings.py”文件中的“MIDDLEWARE”中间件配置项,添加“'django.middleware.locale.LocaleMiddleware'”中间件;

"""
Django settings for cokeblog project.

Generated by 'django-admin startproject' using Django 6.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/6.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-4!y!5%zx4m6^+jv#vv83(+5gog(w3apgaada-oscofx4m5q4t4'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "user.apps.UserConfig",
    "album.apps.AlbumConfig",
    "link.apps.LinkConfig",
    "message.apps.MessageConfig",
    "article.apps.ArticleConfig"
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',                # 使用中文
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'cokeblog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'cokeblog.wsgi.application'


# Database
# https://docs.djangoproject.com/en/6.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}


# Password validation
# https://docs.djangoproject.com/en/6.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/6.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.1/howto/static-files/

STATIC_URL = 'static/'


# Email
# https://docs.djangoproject.com/en/6.1/topics/email/#topic-email-configuration

MAILERS = {
    'default': {
        'BACKEND': 'django.core.mail.backends.console.EmailBackend',
    },
}

配置数据库连接

7、烦请自行准备可用数据库,新建数据库,数据库名烦请自定义,配置文件中设置对应即可;

8、修改项目“cokeblog”应用下的“settings.py”配置文件,设置“DATABASES”项数据库连接信息;注意配置的数据库表要与你的实际情况一致,这里仅供参考;

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_cokeblog',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '192.168.88.155',
        'PORT': '3306'
    }
}

安装“PyMySQL”和“mysqlclient”依赖

9、烦请自行选择一种方式安装“PyMySQL”和“mysqlclient”依赖库;

测试验证

10、启动项目,报错提示 MySQL 版本版本太低,Django v6.1 版本之后需要 MySQL v8.4 或者更高的版本,烦请自行选择升级 MySQL 版本或者降低 Django 版本(例如:Django v6.0.8);

这里选择了降低 Django 版本到“Django v6.0.8”版本;

再次启动项目,能够运行成功;

创建实体测试接口

11、打开“article”子模块中的“models.py”文件,创建一个用于测试接口的博客类别实体类,输入以下内容;

from django.db import models

# Create your models here.

# 定义博客类别实体
class ArticleType(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField('类别名称', max_length=100)

    def __str__(self):
        return self.name

    class Meta:
        # db_table = 'article_type'
        verbose_name = '博客类别管理'
        verbose_name_plural = '博客类别管理'

生成迁移文件

12、PyCharm 工具(I)菜单栏选中“运行 manage.py 任务...(快捷键 Ctrl+Alt+R)”,使用 Django5 manage.py 提供的内置命令,先执行“makemigrations article”生成数据库迁移文件,其他的暂时不用生成,再执行“migrate article”执行迁移文件,同步到数据库中会生成“article_articletype”数据表;

添加测试数据

13、数据库表生成后,目前是没有任何数据信息记录的,所以需要添加一些测试数据,新建查询输入命令,然后运行,执行成功后刷新数据库表,查看测试数据已经成功添加;

insert into `article_articletype` (`id`, `name`) values ('1','语文');
insert into `article_articletype` (`id`, `name`) values ('2','数学');
insert into `article_articletype` (`id`, `name`) values ('3','英语');
insert into `article_articletype` (`id`, `name`) values ('4','政治');
insert into `article_articletype` (`id`, `name`) values ('5','python');

14、修改“article”子模块应用下的“views.py”文件,输入以下内容;

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View


# Create your views here.

# 定义TestView类(导包引入from django.views import View)
class TestView(View):

    def get(self, request):
        # 导包引入from django.http import JsonResponse
        return JsonResponse({'code': 200, 'info': '测试'})

15、在“article”子模块应用下的“urls.py”文件中添加映射,定义下请求的映射关系;

from django.urls import path
from article.views import TestView

urlpatterns = [
    path('test', TestView.as_view(), name='test'),  # test测试
]

16、修改项目“cokeblog”应用下的“urls.py”文件内容,添加“urls”子模块用户模块总映射关系;

"""
URL configuration for cokeblog project.

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/6.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path,include

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

    # 导包引入from django.urls import include
    # 表示前端用户请求是“某某”开头的话会全部分发到对应的模块中,具体的请求再去对应的子模块里去匹配处理
    # path('user/', include('user.urls')),            # 用户模块
    # path('album/', include('album.urls')),          # 相册模块
    # path('link/', include('link.urls')),            # 友情链接模块
    # path('message/', include('message.urls')),      # 留言模块
    path('article/', include('article.urls'))         # 帖子模块
]

17、运行项目,浏览器输入“http://127.0.0.1:8000/article/test”测试验证功能正常;

序列化转换

18、开发业务接口,查询所有用户信息;修改“article”子模块应用下的“views.py”文件内容,查询出所有用户信息,经过测试验证,不可以把查询出来的所有数据传给前端,对象不能直接传递,因为QuerySet 不是一个 JSON 序列化,它必须得是一个 JSON 序列化的才行;

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from article.models import ArticleType


# Create your views here.

# 定义TestView类(导包引入from django.views import View)
class TestView(View):

    def get(self, request):
        # 导包引入from user.models import SysUser,通过objects.all()查询所有用户信息
        articleTypeList_obj = ArticleType.objects.all()
        print(articleTypeList_obj, type(articleTypeList_obj))
        # 导包引入from django.http import JsonResponse
        return JsonResponse({'code': 200, 'info': '测试', 'data': articleTypeList_obj})

19、转化为 JSON 序列化数据信息,修改“article”子模块应用下的“views.py”文件内容,通过调用 all() 方法,返回 QuerySet 类型的对象给数据集,然后通过 values 方法转存为字典类型数据集,最后通过 list 方法,转换成 List 集合再返回给前端;

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from article.models import ArticleType


# Create your views here.

# 定义TestView类(导包引入from django.views import View)
class TestView(View):

    def get(self, request):
        # 导包引入from user.models import SysUser,通过objects.all()查询所有用户信息
        articleTypeList_obj = ArticleType.objects.all()
        print(f'打印查看articleTypeList_obj类型:{type(articleTypeList_obj)},查看: {articleTypeList_obj},')
        # 转存字典,里面的对象转换为了字典类型
        articleTypeList_dict = articleTypeList_obj.values()
        print(f'打印查看articleTypeList_dict类型: {type(articleTypeList_dict)},查看:{articleTypeList_dict}')
        # 把外层的容器转为List
        articleTypeList = list(articleTypeList_dict)
        print(f'打印查看articleTypeList类型: {type(articleTypeList)},查看:{articleTypeList}')
        # 导包引入from django.http import JsonResponse
        return JsonResponse({'code': 200, 'info': '测试', 'data': articleTypeList})

20、浏览器输入“http://127.0.0.1:8000/article/test”测试验证能够正常访问到所有数据,转换后的 List 就是一个标准的 JSON 序列化;

二、前端

前端 Bootstrap

这里前端使用 Bootstrap5 UI 框架,烦请自行下载;Bootstrap 官网:Bootstrap v5 中文文档 · Bootstrap 是全球最受欢迎的 HTML、CSS 和 JS 前端工具库。 | Bootstrap 中文网

创建目录文件

使用 PyCharm 工具打开“cokeblog”项目,在项目根目录下分别创建名称为“static”、“publicStatic”和“media”的目录文件;一般“static”和“publicStatic”用于存放一些静态资源,开发环境放在“publicStatic”目录文件里面,打包部署时会自动打包到“static”目录文件,“media”则用于存放一些媒体资源;

配置静态资源和媒体资源

修改项目“cokeblog”应用下的“settings.py”文件,添加配置静态资源和媒体资源;

"""
Django settings for cokeblog project.

Generated by 'django-admin startproject' using Django 6.1.1.

For more information on this file, see
https://docs.djangoproject.com/en/6.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/6.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/6.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-4!y!5%zx4m6^+jv#vv83(+5gog(w3apgaada-oscofx4m5q4t4'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    "user.apps.UserConfig",
    "album.apps.AlbumConfig",
    "link.apps.LinkConfig",
    "message.apps.MessageConfig",
    "article.apps.ArticleConfig"
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.locale.LocaleMiddleware',                # 使用中文
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'cokeblog.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [BASE_DIR / 'templates']
        ,
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'cokeblog.wsgi.application'


# Database
# https://docs.djangoproject.com/en/6.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db_cokeblog',
        'USER': 'root',
        'PASSWORD': '123456',
        'HOST': '192.168.88.155',
        'PORT': '3306'
    }
}


# Password validation
# https://docs.djangoproject.com/en/6.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/6.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/6.1/howto/static-files/

# STATIC_URL = 'static/'
STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / 'publicStatic']
STATIC_ROOT = BASE_DIR / 'static'

# 设置媒体资源的保存路径
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'

# Email
# https://docs.djangoproject.com/en/6.1/topics/email/#topic-email-configuration

MAILERS = {
    'default': {
        'BACKEND': 'django.core.mail.backends.console.EmailBackend',
    },
}

把已经下载解压的 Bootstrap 开发包放在项目“publicStatic”静态文件路径下,文件名称可自定义,例如:bootstrap5;

测试验证Bootstrap

在项目“templates”目录文件路径下创建一个名称为的“test.html”的 HTML 文件,输入以下内容,测试验证 bootstrap 有没有生效;

<!DOCTYPE html>
<html lang="en">
<head>
    {% load static %}
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{% static 'bootstrap5/css/bootstrap.css' %}" rel="stylesheet">
    <script src="{% static 'bootstrap5/js/bootstrap.js' %}"></script>
</head>
<body>
<button class="btn btn-primary">测试按钮</button>
</body>
</html>

修改“article”子模块应用下的“views.py”文件,输入以下内容;

from django.http import JsonResponse
from django.shortcuts import render
from django.views import View
from article.models import ArticleType


# Create your views here.

# 定义TestView类(导包引入from django.views import View)
class TestView(View):

    def get(self, request):
        # 导包引入from user.models import SysUser,通过objects.all()查询所有用户信息
        # articleTypeList_obj = ArticleType.objects.all()
        # print(f'打印查看articleTypeList_obj类型:{type(articleTypeList_obj)},查看: {articleTypeList_obj},')
        # # 转存字典,里面的对象转换为了字典类型
        # articleTypeList_dict = articleTypeList_obj.values()
        # print(f'打印查看articleTypeList_dict类型: {type(articleTypeList_dict)},查看:{articleTypeList_dict}')
        # # 把外层的容器转为List
        # articleTypeList = list(articleTypeList_dict)
        # print(f'打印查看articleTypeList类型: {type(articleTypeList)},查看:{articleTypeList}')
        # # 导包引入from django.http import JsonResponse
        # return JsonResponse({'code': 200, 'info': '测试', 'data': articleTypeList})

        return render(request, 'test.html')

启动项目,浏览器地址栏输入“http://127.0.0.1:8000/article/test”测试验证,可用查看到已经成功运用到 bootstrap 样式。

未完待续......

转载自 CSDN-专业IT技术社区

原文链接:https://blog.csdn.net/qq_45820603/article/details/171773358

文章来源转载

评论

评论列表

微信小程序
QQ小程序

关于作者

点赞数:0
关注数:0
粉丝:0
文章:0
关注标签:0
加入于:--