Python使用Django实现博客系统完整版

yizhihongxing

下面是关于“Python使用Django实现博客系统完整版”的完整攻略及两条示例说明。

I. Django框架简介

Django是一个Python的开源Web框架,采用了MVT(Model-View-Template)的设计模式,从而使得Web应用的开发更为高效和稳定。通过Django,我们可以快速地构建Web应用,并且Django提供了良好的数据库操作支持,同时还可以轻松地实现前后端的分离,从而使得Web应用的开发更加简便快捷。

II. Django应用创建与配置

为了创建一个基于Django的博客系统,我们需要首先创建一个Django应用,并完成对应的配置。具体步骤如下:

1. 安装Django框架

可以通过在命令行中输入以下命令来安装Django框架:

pip install django

2. 创建Django应用

运行以下命令来创建一个基于Django的应用:

django-admin startproject myblog

其中,myblog是应用的名字,可以根据需求自行修改。

3. 创建Django App

运行以下命令来创建Django App:

cd myblog
python manage.py startapp [appname]

例如,创建名为blog的Django App:

cd myblog
python manage.py startapp blog

4. 配置Django App

myblog/settings.py文件中添加应用blog的配置:

INSTALLED_APPS = [
    'blog',
    ......
]

接着,在myblog/urls.py文件中添加应用blog的路由配置:

from django.urls import path, include

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

III. Django模型设计与数据库操作

博客系统中需要设计文章模型,并完成对应的数据库操作。具体步骤如下:

1. 设计文章模型

blog/models.py文件中设计文章模型:

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=64)
    content = models.TextField()
    created_time = models.DateTimeField(auto_now_add=True)
    last_updated_time = models.DateTimeField(auto_now=True)

2. 数据库迁移

运行以下命令来迁移数据库:

python manage.py makemigrations blog
python manage.py migrate

3. 数据库操作

通过Django的ORM(Object-Relational Mapping)可以实现对数据库的操作。例如,插入一条文章记录的操作如下:

from blog.models import Article

article = Article(title='title', author='author', content='content')
article.save()

IV. Django视图设计与API开发

博客系统中需要设计视图以及API接口,并完成对应的开发。具体步骤如下:

1. 视图设计

blog/views.py文件中设计视图:

from django.shortcuts import render
from blog.models import Article

def index(request):
    articles = Article.objects.all()
    return render(request, 'index.html', {'articles': articles})

2. API接口设计

blog/views.py文件中设计API接口:

from django.http import JsonResponse
from blog.models import Article

def articles(request):
    articles = Article.objects.all()
    data = [
        {'title': article.title, 'author': article.author, 'content': article.content}
        for article in articles
    ]
    return JsonResponse({'data': data})

3. URL配置

blog/urls.py文件中对应的URL配置:

from django.urls import path
from blog import views

urlpatterns = [
    path('', views.index, name='index'),
    path('api/articles', views.articles, name='api_articles'),
]

V. 博客系统前端实现

博客系统需要通过前端实现,具体步骤如下:

1. 模板设计

blog/templates目录下设计视图对应的模板文件,例如index.html

{% for article in articles %}
<div class="article">
    <h2>{{ article.title }}</h2>
    <p>{{ article.author }}</p>
    <p>{{ article.created_time }}</p>
    <p>{{ article.content }}</p>
</div>
{% endfor %}

2. API调用

通过JavaScript代码调用API接口,例如:

fetch('/api/articles')
  .then(response => response.json())
  .then(data => {
    console.log(data)
  })

VI. 示例说明 - 一个简单的博客系统

下面是通过Django框架实现的一个简单的博客系统的示例,包含后端和前端实现。具体步骤如下:

后端实现

1. 创建Django应用

运行以下命令来创建一个名为blog的Django应用:

django-admin startproject myblog
cd myblog
python manage.py startapp blog

2. 安装依赖

新建一个名为requirements.txt的文件,添加以下内容:

Django==3.1.7
django-cors-headers==3.7.0
mysqlclient==2.0.3
pytz==2021.1

运行以下命令来安装依赖:

pip install -r requirements.txt

3. 设计文章模型

blog/models.py文件中设计文章模型:

from django.db import models

class Article(models.Model):
    title = models.CharField(max_length=255)
    author = models.CharField(max_length=64)
    content = models.TextField()
    created_time = models.DateTimeField(auto_now_add=True)
    last_updated_time = models.DateTimeField(auto_now=True)

4. 数据库迁移

运行以下命令来迁移数据库:

python manage.py makemigrations blog
python manage.py migrate

5. 视图设计

blog/views.py文件中设计视图:

from django.shortcuts import render
from blog.models import Article

def index(request):
    articles = Article.objects.all()
    return render(request, 'index.html', {'articles': articles})

6. API接口设计

blog/views.py文件中设计API接口:

from django.http import JsonResponse
from blog.models import Article

def articles(request):
    articles = Article.objects.all()
    data = [
        {'title': article.title, 'author': article.author, 'content': article.content}
        for article in articles
    ]
    return JsonResponse({'data': data})

7. URL配置

blog/urls.py文件中对应的URL配置:

from django.urls import path
from blog import views

urlpatterns = [
    path('', views.index, name='index'),
    path('api/articles', views.articles, name='api_articles'),
]

8. 配置CORS

myblog/settings.py文件中添加以下配置:

INSTALLED_APPS = [
    ...
    'corsheaders',
]

MIDDLEWARE = [
    ...
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
]

CORS_ORIGIN_ALLOW_ALL = True

9. 运行Django服务器

运行以下命令来启动Django服务器:

python manage.py runserver

前端实现

我们使用Vue.js作为前端开发框架,下面是具体的实现步骤:

1. 安装Vue.js

可以通过以下命令来安装Vue.js:

npm install vue

2. 设计页面模板

新建一个名为index.html的文件,添加以下内容:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Blog</title>
</head>
<body>
    <div id="app">
        <h1>My Blog</h1>
        <div v-for="(article, index) in articles" :key="index" class="article">
            <h2>{{ article.title }}</h2>
            <p>{{ article.author }}</p>
            <p>{{ article.created_time }}</p>
            <p>{{ article.content }}</p>
        </div>
    </div>

    <script src="https://unpkg.com/vue@next"></script>
    <script>
        const app = Vue.createApp({
            data() {
                return {
                    articles: []
                }
            },
            async mounted() {
                const response = await fetch('/api/articles')
                const data = await response.json()
                this.articles = data.data
            }
        })
        app.mount('#app')
    </script>
</body>
</html>

3. 运行前端服务器

运行以下命令来启动前端服务器:

python -m http.server

4. 查看结果

在浏览器中访问http://localhost:8000,即可看到博客系统的展示结果。

VII. 示例说明 - 博客系统添加登录验证

下面是在基于Django实现的博客系统中添加登录验证的示例,具体步骤如下:

1. 运行以下命令来创建一个名为users的Django应用:

python manage.py startapp users

2. 在users/models.py文件中设计用户模型:

from django.contrib.auth.models import AbstractUser

class User(AbstractUser):
    pass

3. 迁移数据库:

python manage.py makemigrations users
python manage.py migrate

4. 在myblog/settings.py文件中添加以下配置:

INSTALLED_APPS = [
    ...
    'users',
]

AUTH_USER_MODEL = 'users.User'

5. 在users/views.py文件中设计登录API:

from django.contrib.auth.views import LoginView

class MyLoginView(LoginView):
    template_name = 'login.html'

6. 在users/urls.py文件中设计登录路由:

from django.urls import path
from . import views

urlpatterns = [
    path('login/', views.MyLoginView.as_view(), name='login'),
]

7. 创建login.html模板文件:

{% extends 'base.html' %}

{% block content %}
<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit">Login</button>
</form>
{% endblock %}

8. 在myblog/urls.py文件中添加如下配置:

from django.urls import path, include

urlpatterns = [
    ...
    path('users/', include('django.contrib.auth.urls')),
]

9. 修改blog/views.py文件中的函数index

from django.shortcuts import render
from django.contrib.auth.decorators import login_required
from blog.models import Article

@login_required
def index(request):
    articles = Article.objects.all()
    return render(request, 'index.html', {'articles': articles})

10. 在blog/templates/base.html模板文件中添加登录和登出链接:

{% if user.is_authenticated %}
    <a href="{% url 'logout' %}">Logout</a>
{% else %}
    <a href="{% url 'login' %}">Login</a>
{% endif %}

11. 运行Django服务器并查看结果:

python manage.py runserver

在浏览器中访问http://localhost:8000,即可看到博客系统的展示结果,并且需要登录才能查看文章。

本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:Python使用Django实现博客系统完整版 - Python技术站

(0)
上一篇 2023年5月16日
下一篇 2023年5月16日

相关文章

  • Django学习笔记-Django1.11 python manage.py migrate执行出错

    学习python编程 从入门到实践第18章时,创建数据库失败  python manage.py migrate 执行失败,报错: ‘%s=%s’ % (k, v) for k, v in params.items(), SyntaxError: Generator expression must be parenthesized 解决方法: 找到widge…

    Django 2023年4月10日
    00
  • python Django连接MySQL数据库做增删改查

    下面是一份完整攻略。 环境搭建 首先我们需要安装 Django 和 MySQL 驱动。安装 Django 可以使用 pip 包管理器,可以在终端中运行以下命令实现: pip install Django 安装 MySQL 驱动则需要先安装 mysqlclient 或者 PyMySQL。推荐使用mysqlclient,这里以mysqlclient为例,可以在终…

    Django 2023年5月16日
    00
  • django使用uwsgi启动

    django默认是wsgi启动,不能利用到多核执行效率很低,通过uwsgi来解决这个问题。   python虚拟环境安装配置: https://www.cnblogs.com/zezhou/p/14509198.html python虚拟环境使用操作: https://www.cnblogs.com/zezhou/p/14509203.html   安装uw…

    Django 2023年4月11日
    00
  • Django ORM查询之extra查询

    extra(select=None, where=None,params=None,tables=None, order_by=None, select_params=None) 有些情况下,Django的查询语法难以简单的表达复杂的 WHERE 子句,QuerySet生成的SQL从句中注入新子句。 参数之SELECT   The select 参数可以让你…

    Django 2023年4月13日
    00
  • django的json返回值带有汉字的处理

    原因:simpleJson把utf-8编码的字符串直接转成了unicode,但却是按字节来转的,不是真正的unicode 下面是转化为unicode的代码 from django.http import HttpResponse from django.utils import simplejson from django.conf import setti…

    Django 2023年4月13日
    00
  • django实现api跨域请求访问

    第一步:安装 django-cors-headers pip install django-cors-headers   第二步:配置settings.py文件 ———————–和前端配合指定可以跨域的用户—————————- from corsheaders.defaults import …

    Django 2023年4月11日
    00
  • Django框架简介(MVC框架和MTV框架)

    MVC,全名是Model View Controller,是软件工程中的一种软件架构模式,把软件系统分为三个基本部分:模型(Model)、视图(View)和控制器(Controller),具有耦合性低、重用性高、生命周期成本低等优点。 Django框架的设计模式借鉴了MVC框架的思想,也是分成三部分,来降低各个部分之间的耦合性。   借用介绍MVC:http…

    2023年4月9日
    00
  • Django + Celery 实现动态配置定时任务

      哈喽,今天给大家分享一篇Django+Celery实现动态配置定时任务,因为最近也是无意间看到一位大佬关于这块的文章,然后自己觉得不错,也想学习写一下,然后最终实现功能是在前端页面统一管理计划任务,大家可以在admin管理页面设置,也可以在自己写的前端页面删除添加编辑,实时生效,还可以监控这些监控任务是否运行成功失败。  补充:如果大家对celery不熟…

    Django 2023年4月11日
    00
合作推广
合作推广
分享本页
返回顶部