Python+Django搭建個(gè)人博客(5)-Django模型

認(rèn)識(shí)數(shù)據(jù)庫

  • 存儲(chǔ)數(shù)據(jù)的倉庫
  • 什么是數(shù)據(jù)?
    • 學(xué)生的姓名、性別、成績(jī);
    • 用戶的銀行卡號(hào)、密碼、余額、交易記錄
    • 網(wǎng)站的登錄賬號(hào)、密碼、評(píng)論
    • 游戲的用戶名、裝備、屬性、等級(jí)

數(shù)據(jù)是如何存在數(shù)據(jù)庫中

  • 一張張表存儲(chǔ)各種信息

  • 表與表之間還可能有不同的聯(lián)系

    image
    image

Django中的數(shù)據(jù)庫

  • 打開blog應(yīng)用里的models.py文件

  • 加入以下內(nèi)容

    #繼承于models.Model, 新建了叫post的表格
    class Post(models.Model):
    
        # 有title屬性
        title=modesl.CharField(max_length=80)
    
  • 同步數(shù)據(jù)庫

    • 根目錄運(yùn)行python manage.py makemigrations
    • 得到如下提示,表示創(chuàng)建了Post模型


      image
    • 繼續(xù)命令運(yùn)行python manage.py migrate
    • 得到如下提示


      image

利用admin后臺(tái)系統(tǒng)管理數(shù)據(jù)

  • 運(yùn)行python manage.py runserver啟動(dòng)服務(wù)器

  • 修改blog文件夾中的admin.py

    from django.contrib import admin
    from .models import Post
    
    # Register your models here.
    admin.site.register(Post)
    
  • 登錄admin后臺(tái)系統(tǒng)

    • 訪問http://127.0.0.1:8000/admin,會(huì)看到新增了一個(gè)欄目

      image
  • admin后臺(tái)系統(tǒng)管理

    • 點(diǎn)擊Posts進(jìn)入,可以看見還沒有內(nèi)容發(fā)布過

    • 點(diǎn)擊ADD POST,可直接添加一個(gè)Post的title


      image
    • 在title中輸入內(nèi)容,SAVE保存,保存后叫Post project(1),不直觀

    • 修改blog文件夾里的models.py

      class Post(models.Model):
      
      # 有title屬性
      title=models.CharField(max_length=80)
      
      def __str__(self):
              return self.title
      

      此時(shí),這里就展示的是你輸入的title的內(nèi)容

      image

設(shè)計(jì)博文模型

  • 一篇博客相關(guān)的信息如下:

    • 標(biāo)題
    • 副標(biāo)題
    • 作者
    • 發(fā)表日期
    • 標(biāo)簽
    • 分類
    • 博文內(nèi)容
    • 博文鏈接
    • 點(diǎn)贊數(shù)(可選)
    • 閱讀量(可選)
  • Django中可用的各類模型

    image

    目前常用:
    - CharField 簡(jiǎn)單文字模型
    - DateTiemField 時(shí)間模型
    - TextField 大段文字模型

  • 設(shè)計(jì)博文模型簡(jiǎn)易版

    image

    這樣設(shè)計(jì)存在什么問題?

    作者、標(biāo)簽、分類存在同一個(gè)表中,會(huì)造成大量重復(fù)的內(nèi)容、不易檢索、不易修改。

    image
  • 設(shè)計(jì)博文模型進(jìn)階版

    image

博文基礎(chǔ)模版

  • models.py添加一些基礎(chǔ)模型

    class Post(models.Model):
    
        title=models.CharField(max_length=80)
        subtitle=CharField(max_length=120)
        publish_date=models.DateTimeField()
        content=models.TextField()
        link=models.CharField(max_length=200)
    
        def __str__(self):
                return self.title
    
  • 關(guān)聯(lián)作者模型

    from django.db import models
    from django.contrib.auth.models import User`
    
    class Post(models.Model):
    
    title=models.CharField(max_length=80)
    subtitle=CharField(max_length=120)
    publish_date=models.DateTimeField()
    content=models.TextField()
    link=models.CharField(max_length=200)
    # 利用ForeignKey()即把字段author關(guān)聯(lián)另外一個(gè)模型
    author=models.ForeignKey(User,on_delete=models.CASCADE) 
    
    def __str__(self):
            return self.title
    

新建分類模型和標(biāo)簽?zāi)P?/h3>

添加兩個(gè)class,同時(shí)補(bǔ)充Post類

class Category(models.Model):
    """分類"""
    name = models.CharField(max_length=100)
    def __str__(self):
            return self.name

class Tag(models.Model):
    """標(biāo)簽"""
    name = models.CharField(max_length=100)
    def __str__(self):
            return self.name

class Post(models.Model):
    title=models.CharField(max_length=80)
    subtitle=models.CharField(max_length=120)
    publish_date=models.DateTimeField()
    content=models.TextField()
    link=models.CharField(max_length=200)
    # 利用ForeignKey()即可關(guān)聯(lián)另外一個(gè)模型
    author=models.ForeignKey(User,on_delete=models.CASCADE) 
    category=models.ForeignKey(Category,on_delete=models.CASCADE) 
    # 利用MangToManyField()關(guān)聯(lián)另外一個(gè)模型
    tag=models.ManyToManyField(Tag,blank=True)

    def __str__(self):
            return self.title
  • ForeignKey()和ManyToManyField()的區(qū)別

    • 一對(duì)多的關(guān)系,使用ForeignKey()

      一篇文章只有一個(gè)分類,一個(gè)分類下有多個(gè)文章

      image
    • 多對(duì)多的關(guān)系,使用MangToManyField()

      一個(gè)文章可以有多個(gè)標(biāo)簽,一個(gè)標(biāo)簽會(huì)對(duì)應(yīng)多個(gè)文章


      image
  • 新建了2個(gè)模型,所以要在admin.py中添加

    from django.contrib import admin
    from .models import Post
    from .models import Category
    from .models import Tag
    
    # Register your models here.
    
    admin.site.register(Category)
    admin.site.register(Tag)
    admin.site.register(Post)
    

運(yùn)行Django的管理命令

  • 只要修改了models.py文件,都需要運(yùn)行python manage.py makemigrations

    會(huì)提示:


    image

    意思為:

    image

    選擇1方案,填寫默認(rèn)值1,除了時(shí)datetime填timezone.now

    創(chuàng)建成功:

    image
  • 每次運(yùn)行完python manage.py makemigrations,都要運(yùn)行python manage.py magrate

  • 注意:如果這里運(yùn)行python manage.py magrate時(shí)一直報(bào)錯(cuò),難以結(jié)局,可以嘗試刪掉my_blog下的db.sqlite3文件,再重新運(yùn)行python manage.py magrate,再重新創(chuàng)建admin賬號(hào)即可。

admin后臺(tái)查看

  • 進(jìn)入到后臺(tái)管理,可以看到新增了Category、Tag

    image
  • 點(diǎn)擊Posts-Add post,新增了我們寫的字段

    image
  • 添加Category,比如添加編程分類

![image](https://upload-images.jianshu.io/upload_images/12041448-3c7cf803756c4e3d?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
  • 添加Tag,比如添加Python標(biāo)簽

    image
  • 再進(jìn)入到post,可以發(fā)現(xiàn)Category可選編程,Tag可以選Python,直接點(diǎn)擊?添加也可

    image

從數(shù)據(jù)庫提取真正的博文信息

  • 修改views.py
    • 引入Post模型
      from .models import Post

    • 列出全部的Post數(shù)據(jù),按發(fā)表日期倒序排列
      Post.objects.all().order_by('-publish_date')

    • 修改如下:

      from django.shortcuts import render
      from django.http import HttpResponse
      from .models import Post
      
      # Create your views here.
      
      def index(request):
          post_list=Post.objects.all().order_by('-publish_date')
          return render(request,'blog/index.html',{'post_list':post_list})
      

設(shè)計(jì)博客詳情頁網(wǎng)址

  • 每篇博文有一個(gè)英文的網(wǎng)址,如127.0.0.1:8080/blog/django-course-1

  • 后臺(tái)link只需要填django-course-1部分

  • 修改index.html的博客詳情頁鏈接,設(shè)計(jì)為blog/link

    <a href="/blog/{{post.link}}">

  • 將時(shí)間那里改為我們的時(shí)間變量

    <p class="post-meta">Posted by
            <a href="#">{{post.author}}</a>
            {{post.publish_date}}</p>
    
  • 修改urls.py的網(wǎng)址配置,將blog_detail的參數(shù)改為blog_link
    path('<int:blog_link>',views.blog_detail,name='blog_detail'),

  • 修改views.py
    from django.shortcuts import render,get_object_or_404

    get_object_or_404表示從某個(gè)模型根據(jù)關(guān)鍵字提取某段數(shù)據(jù),找不到返回?cái)?shù)據(jù),就返回404頁面

    def blog_detail(request,blog_link):
        post=get_object_or_404(Post,link=blog_link)
        return HttpResponse(post.content)
    
  • 在管理后臺(tái)配置一篇博客,看下效果

    image
    image

添加博客詳情頁模版

我們下載的模版中,有一個(gè)post.html的文件,就是我們博客詳情頁的模版,把它用到我們項(xiàng)目中,放在我們app的/templates/blog下.

  • 修改views.py

    def blog_detail(request,blog_link):
    
        post=get_object_or_404(Post,link=blog_link)
        # 返回博文詳情
        return render(request,'blog/post.html',{'post':post})
    
  • 修改post.html

    同我們修改index.html一樣,把js、css、img的路徑進(jìn)行修改:

    <link href="{%static 'blog/vendor/bootstrap/css/bootstrap.min.css' %}" rel="stylesheet">

    修改title、標(biāo)題、副標(biāo)題、作者、正文、時(shí)間:

![image](https://upload-images.jianshu.io/upload_images/12041448-80c6cf86d6389b21?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


![image](https://upload-images.jianshu.io/upload_images/12041448-c1880a0405574a05?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)


![image](https://upload-images.jianshu.io/upload_images/12041448-e98dde80a216caf5?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

更漂亮的正文排版

方式一:在后臺(tái)的content中直接寫html代碼,比較麻煩;

方式二:采用Markdown格式編寫博文(推薦)

  • 安裝markdown模塊 pip install markdown2
  • 修改views.py
    def blog_detail(request,blog_link):
    
        post=get_object_or_404(Post,link=blog_link)
        post.content = markdown2.markdown(post.content)
        # 返回博文詳情
        return render(request,'blog/post.html',{'post':post})
    
  • 后臺(tái)博客content中用markdown語法進(jìn)行編輯
![image](https://upload-images.jianshu.io/upload_images/12041448-a186b0859874f986?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

![image](https://upload-images.jianshu.io/upload_images/12041448-065707266d6d84c6?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

發(fā)現(xiàn)沒有對(duì)標(biāo)簽進(jìn)行渲染,如何解決?

在post.html中的`{{post.content}}`修改為`{{post.content|safe}}`

![image](https://upload-images.jianshu.io/upload_images/12041448-2662420cd0abf804?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

    
![image](https://upload-images.jianshu.io/upload_images/12041448-6951cad5b72d5aec?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)

**遺留問題,這里貌似不支持代碼塊的展示,待解決**

調(diào)整url

現(xiàn)在的url是127.0.0.1:8000/blog/首頁,我們希望127.0.0.1:8000就是首頁

  • 修改my_blog的urls.py
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('',include('blog.urls')),
    ]
    
  • 修改blog的urls.py
    urlpatterns = [
        path('',views.index,name='blog_index'),
        path('blog/<slug:blog_link>/',views.blog_detail,name='blog_detail'),
    ]
    

如何把網(wǎng)站對(duì)外發(fā)布

  • 購買服務(wù)器和域名
    • 服務(wù)器見文章最前面部分

    • 域名

      • 國內(nèi):wanwang.aliyun.com
      • 國外:godaddy.com
      • .cn/.com等域名需要實(shí)名認(rèn)證
    • 服務(wù)器或者域名在國內(nèi)買的,需要進(jìn)行備案,沒有備案的話,有可能會(huì)被墻掉

    • 購買后,設(shè)置域名解析,表示該域名指向的服務(wù)器ip地址

      image

Django部署

(不詳細(xì)講,自行g(shù)oogle)

  1. 安裝uwsgi

  2. 配置uwsgi.ini

    示例:

    image
  3. 安裝nginx

  4. 配置nginx

  5. 啟動(dòng)uwsgi uwsgi --ini uwsgi.ini

  6. 啟動(dòng)nginx

服務(wù)器使用中常見的幾個(gè)問題

image
  1. 可能是數(shù)據(jù)庫沒有填寫我們的hosts
  2. 80端口可能之前已經(jīng)被打開,關(guān)掉80端口即可
  3. ip地址沒填對(duì),要公網(wǎng)的ip地址
  4. 連上一段時(shí)間沒有操作也會(huì)自動(dòng)斷掉
  5. 網(wǎng)絡(luò)連接問題
  6. 安裝一個(gè)screen應(yīng)用

作業(yè)

image
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容