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-增加文章評論模塊

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章