Django个人博客搭建2-编写文章Model模型,View视图

Django个人博客搭建1-创建Django项目和第一个App
Django个人博客搭建2-编写文章Model模型,View视图
Django个人博客搭建3-创建superuser并向数据库中添加数据并改写视图
Django个人博客搭建4-配置使用 Bootstrap 4 改写模板文件
Django个人博客搭建5-编写文章详情页面并支持markdown语法
Django个人博客搭建6-对文章进行增删查改
Django个人博客搭建7-对用户登陆注册等需求的实现
Django个人博客搭建8-优化文章模块
Django个人博客搭建9-增加文章评论模块
1. 将数据库设置为mysql
Django数据库默认为sqlite,我们可以修改成其他数据库例如mysql
修改settings.py中的DATABASES

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "myblog",     # 数据库名
        'USER': 'root',     # 用户名
        'PASSWORD':'',      # 数据库密码
        'HOST': 'localhost',    # 数据库服务器ip
        'PORT': '3306'      # 端口
    }
}

2. 编写 Model. py
打开article/models.py输入如下代码:


# Create your models here.
from django.db import models

# 导入内建的User模型
from django.contrib.auth.models import User
from django.utils import timezone

# 博客文章数据模型
class ArticlePost(models.Model):
    # 文章作者。参数on_delete 用于指定数据删除的方式,避免两个关联表数据不一致
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    # 文章标题
    title = models.CharField(max_length=100)

    # 文章正文
    body = models.TextField()

    created = models.DateTimeField(default=timezone.now())

    # 文章更新时间 参数 auto_now=True 指定每次数据更新时自动写入当前时间
    updated = models.DateTimeField(auto_now=True)

使用 ForeignKey定义一个关系。这将告诉 Django,每个(或多个) ArticlePost 对象都关联到一个 User 对象。Django本身具有一个简单完整的账号系统(User),足以满足一般网站的账号申请建立权限群组等基本功能。

ArticlePost类定义了一篇文章所必须具备的要素:作者、标题、正文、创建时间以及更新时间。我们还可以额外再定义一些内容,规范ArticlePost中数据的行为。加入以下代码:

class ArticlePost(models.Model):
    # 文章作者。参数on_delete 用于指定数据删除的方式,避免两个关联表数据不一致
    author = models.ForeignKey(User, on_delete=models.CASCADE)

    # 文章标题
    title = models.CharField(max_length=100)

    # 文章正文
    body = models.TextField()

    created = models.DateTimeField(default=timezone.now())

    # 文章更新时间 参数 auto_now=True 指定每次数据更新时自动写入当前时间
    updated = models.DateTimeField(auto_now=True)
	# 增加如下代码
    # 内部类class Meta用于给model定义元数据
    class Meta:
        # ordering 指定模型返回的数据的排列顺序
        # ’-created‘ 表明数据应该以倒叙排列
        ordering = ('-created',)

    def __str__(self):
        return self.title

内部类Meta中的ordering定义了数据的排列方式。-created表示将以创建时间的倒序排列,保证了最新的文章总是在网页的最上方。注意ordering是元组,括号中只含一个元素时不要忘记末尾的逗号。

__str__方法定义了需要表示数据时应该显示的名称。给模型增加 __str__方法是很重要的,它最常见的就是在Django管理后台中做为对象的显示值。因此应该总是返回一个友好易读的字符串。后面会看到它的好处。

内部类(Meta)
内部类class Meta用来使用类提供的模型元数据。模型元数据是“任何不是字段的东西”,例如排序选项ordering、数据库表名db_table、单数和复数名称verbose_nameverbose_name_plural。要不要写内部类是完全可选的,当然有了它可以帮助理解并规范类的行为。

在class ArticlePost中我们使用的元数据ordering = (’-created’,),表明了每当我需要取出文章列表,作为博客首页时,按照** -created**(即文章创建时间,负号标识倒序)来排列,保证了最新文章永远在最顶部位置。

3. 数据迁移
进入到 manage.py同级目录下输入:

python manage.py makemigrations

(如果你用的是python3,那么可能会看到如下报错

F:\PycharmProject\myblog\myblog>python manage.py makemigrations
Traceback (most recent call last):
  File "D:\Python3.6.5\lib\site-packages\django\db\backends\mysql\base.py", line 15, in <module>
    import MySQLdb as Database
ModuleNotFoundError: No module named 'MySQLdb'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 15, in <module>
    execute_from_command_line(sys.argv)
  File "D:\Python3.6.5\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line
    utility.execute()
  File "D:\Python3.6.5\lib\site-packages\django\core\management\__init__.py", line 357, in execute
    django.setup()
  File "D:\Python3.6.5\lib\site-packages\django\__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "D:\Python3.6.5\lib\site-packages\django\apps\registry.py", line 112, in populate
    app_config.import_models()
  File "D:\Python3.6.5\lib\site-packages\django\apps\config.py", line 198, in import_models
    self.models_module = import_module(models_module_name)
  File "D:\Python3.6.5\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "D:\Python3.6.5\lib\site-packages\django\contrib\auth\models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "D:\Python3.6.5\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "D:\Python3.6.5\lib\site-packages\django\db\models\base.py", line 101, in __new__
    new_class.add_to_class('_meta', Options(meta, app_label))
  File "D:\Python3.6.5\lib\site-packages\django\db\models\base.py", line 304, in add_to_class
    value.contribute_to_class(cls, name)
  File "D:\Python3.6.5\lib\site-packages\django\db\models\options.py", line 203, in contribute_to_class
    self.db_table = truncate_name(self.db_table, connection.ops.max_name_length())
  File "D:\Python3.6.5\lib\site-packages\django\db\__init__.py", line 33, in __getattr__
    return getattr(connections[DEFAULT_DB_ALIAS], item)
  File "D:\Python3.6.5\lib\site-packages\django\db\utils.py", line 202, in __getitem__
    backend = load_backend(db['ENGINE'])
  File "D:\Python3.6.5\lib\site-packages\django\db\utils.py", line 110, in load_backend
    return import_module('%s.base' % backend_name)
  File "D:\Python3.6.5\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "D:\Python3.6.5\lib\site-packages\django\db\backends\mysql\base.py", line 20, in <module>
    ) from err
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module.
Did you install mysqlclient?

F:\PycharmProject\myblog\myblog>

很明显是没有找到MySQLdb模块
因为python3中是没有MySQLdb模块,用pymysql代替了,在__init__中添加如下代码:

import pymysql
pymysql.install_as_MySQLdb()

再次进行数据库迁移:

F:\PycharmProject\myblog\myblog>python manage.py makemigrations
System check identified some issues:

WARNINGS:
article.ArticlePost.created: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Migrations for 'article':
  article\migrations\0001_initial.py
    - Create model ArticlePost

F:\PycharmProject\myblog\myblog>

可以看见成功进行了迁移
然后迁移到数据库中

F:\PycharmProject\myblog\myblog>python manage.py migrate
System check identified some issues:

WARNINGS:
article.ArticlePost.created: (fields.W161) Fixed default value provided.
        HINT: It seems you set a fixed date / time / datetime value as default for this field. This may not be what you want. If you want to have the current date as default, use `django.utils.timezone.now`
Operations to perform:
  Apply all migrations: admin, article, auth, contenttypes, sessions
Running migrations:
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying admin.0003_logentry_add_action_flag_choices... OK
  Applying article.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying auth.0008_alter_user_username_max_length... OK
  Applying auth.0009_alter_user_last_name_max_length... OK
  Applying sessions.0001_initial... OK

F:\PycharmProject\myblog\myblog>

迁移到数据库成功

4. 编写视图函数 article/views.py

from django.shortcuts import render

# Create your views here.

from django.http import HttpResponse

# 视图函数
def article_list(request):
    return HttpResponse("Hello World!")

将用户请求的url关联起来(修改article/urls.py)

# 引入views.py
# 引入path
from django.urls import path
from . import views
# 正在部署的应用的名称
app_name = 'article'
urlpatterns = [
    # path函数将url映射到视图
    path('article-list/', views.article_list, name='article_list'),
]

修改后运行服务:
在这里插入图片描述
目录

Django个人博客搭建1-创建Django项目和第一个App
Django个人博客搭建2-编写文章Model模型,View视图
Django个人博客搭建3-创建superuser并向数据库中添加数据并改写视图
Django个人博客搭建4-配置使用 Bootstrap 4 改写模板文件
Django个人博客搭建5-编写文章详情页面并支持markdown语法
Django个人博客搭建6-对文章进行增删查改
Django个人博客搭建7-对用户登陆注册等需求的实现
Django个人博客搭建8-优化文章模块
Django个人博客搭建9-增加文章评论模块

猜你喜欢

转载自blog.csdn.net/weixin_43249914/article/details/86765350