Django 開發(fā)內(nèi)容管理系統(tǒng)_自強學堂

用Django開發(fā)一個簡易的內(nèi)容管理系統(tǒng),比如顯示新聞的列表,點擊進去可以看內(nèi)容詳情等,新聞發(fā)布網(wǎng)站。

1.環(huán)境搭建
開發(fā)會用 virtualenv 來管理多個開發(fā)環(huán)境,virtualenvwrapper 使得virtualenv變得更好用

E:\ScienceSoft\Python\Django>mkvirtualenv ContentManagePro
Using base prefix 'c:\\users\\administrator\\appdata\\local\\programs\\python\\p
ython35'
New python executable in C:\Users\Administrator\Envs\ContentManagePro\Scripts\py
thon.exe
Installing setuptools, pip, wheel...done.

(ContentManagePro) E:\ScienceSoft\Python\Django>

二,安裝軟件,開發(fā) minicms 項目
2.1 創(chuàng)建一個開發(fā)環(huán)境 minicms

windows

mkvirtualenv minicms


image.png
(ContentManagePro) E:\ScienceSoft\Python\Django>mkvirtualenv minicms
Using base prefix 'c:\\users\\administrator\\appdata\\local\\programs\\python\\p
ython35'
New python executable in C:\Users\Administrator\Envs\minicms\Scripts\python.exe
Installing setuptools, pip, wheel...done.

路徑在C:\Users\Administrator\Envs\minicms

image.png

補充:正確的虛擬環(huán)境創(chuàng)建和激活方式如下:

# 進入python的安裝路徑中python文件加下的scripts
# http://www.cnblogs.com/ttrrpp/p/6690253.html
C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts>activate.b
at
'activate.bat' 不是內(nèi)部或外部命令,也不是可運行的程序
或批處理文件。

C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts>virtualenv env #這一步很重要
Using base prefix 'c:\\users\\administrator\\appdata\\local\\programs\\python\\p
ython35'
New python executable in C:\Users\Administrator\AppData\Local\Programs\Python\Py
thon35\Scripts\env\Scripts\python.exe
Installing setuptools, pip, wheel...done.

C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts>cd C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts\env\Scripts

C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts\env\Script
s>activate.bat

(env) C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts\env\
Scripts>
4、像平常一樣安裝包,比如:

pip install requests

(env) C:\Users\Administrator\AppData\Local\Programs\Python\Python35\Scripts\env
Scripts>pip install requests
安裝成功
也可以在其他盤創(chuàng)建虛擬環(huán)境:
(minicms) E:\ScienceSoft\Python>virtualenv env
Using base prefix 'c:\users\administrator\appdata\local\programs\python\p
ython35'
New python executable in E:\ScienceSoft\Python\env\Scripts\python.exe
Installing setuptools, pip, wheel...done.

(minicms) E:\ScienceSoft\Python>cd E:\ScienceSoft\Python\env\Scripts

(minicms) E:\ScienceSoft\Python\env\Scripts>activate.bat

(env) E:\ScienceSoft\Python\env\Scripts>


5、如果你在虛擬環(huán)境中暫時完成了工作,則可以停用它:

deactivate

2.2 安裝 Django:我已經(jīng)安裝過
2.3 創(chuàng)建項目 minicms 和 應用 news


E:\ScienceSoft\Python\Django>pip install virtualenv virtualenvwrapper
Collecting virtualenv
  Downloading virtualenv-15.1.0-py2.py3-none-any.whl (1.8MB)
    34% |███████████▏                    | 634kB 465kB/s eta 0:00:03
    35% |███████████▍                    | 645kB 550kB/s eta 0:00:03
    35% |███████████▌                    | 655kB 461kB/s eta 0:00:03
    36% |███████████▊                    | 665kB 457kB/s eta 0:00:03
    37% |███████████▉                    | 675kB 568kB/s eta 0:00:03
    37% |████████████                    | 686kB 433kB/s eta 0:00:03
    38% |████████████▎                   | 696kB 432kB/s eta 0:00:0
    38% |████████████▍                   | 706kB 628kB/s eta 0:00:0
    39% |████████████▋                   | 716kB 624kB/s eta 0:00:0
    39% |████████████▉                   | 727kB 485kB/s eta 0:00:0
    40% |█████████████                   | 737kB 441kB/s eta 0:00:0
    41% |█████████████▏                  | 747kB 492kB/s eta 0:00:
    41% |█████████████▎                  | 757kB 419kB/s eta 0:00:
    42% |█████████████▌                  | 768kB 412kB/s eta 0:00:
    42% |█████████████▊                  | 778kB 433kB/s eta 0:00:
    43% |█████████████▉                  | 788kB 565kB/s eta 0:00:
    43% |██████████████                  | 798kB 562kB/s eta 0:00:
    44% |██████████████▏                 | 808kB 525kB/s eta 0:00
    44% |██████████████▍                 | 819kB 465kB/s eta 0:00
    45% |██████████████▋                 | 829kB 598kB/s eta 0:00
    46% |██████████████▊                 | 839kB 581kB/s eta 0:00
    46% |███████████████                 | 849kB 511kB/s eta 0:00
    47% |███████████████▏                | 860kB 787kB/s eta 0:0
    47% |███████████████▎                | 870kB 530kB/s eta 0:0
    48% |███████████████▌                | 880kB 527kB/s eta 0:0
    48% |███████████████▋                | 890kB 247kB/s eta 0:0
    49% |███████████████▉                | 901kB 247kB/s eta 0:0
    50% |████████████████                | 911kB 254kB/s eta 0:0
    50% |████████████████▏               | 921kB 263kB/s eta 0:
    51% |████████████████▍               | 931kB 193kB/s eta 0:
    51% |████████████████▋               | 942kB 201kB/s eta 0:
    52% |████████████████▊               | 952kB 211kB/s eta 0:
    52% |█████████████████               | 962kB 208kB/s eta 0:
    53% |█████████████████               | 972kB 240kB/s eta 0:
    53% |█████████████████▎              | 983kB 242kB/s eta 0
    54% |█████████████████▌              | 993kB 501kB/s eta 0
    55% |█████████████████▋              | 1.0MB 509kB/s eta 0
    55% |█████████████████▉              | 1.0MB 517kB/s eta 0
    56% |██████████████████              | 1.0MB 547kB/s eta 0
    56% |██████████████████▏             | 1.0MB 2.2MB/s eta
    57% |██████████████████▍             | 1.0MB 2.4MB/s eta
    57% |██████████████████▌             | 1.1MB 2.1MB/s eta
    58% |██████████████████▊             | 1.1MB 2.5MB/s eta
    59% |███████████████████             | 1.1MB 2.8MB/s eta
    59% |███████████████████             | 1.1MB 2.8MB/s eta
    60% |███████████████████▎            | 1.1MB 652kB/s eta
    60% |███████████████████▍            | 1.1MB 643kB/s eta
    61% |███████████████████▋            | 1.1MB 562kB/s eta
    61% |███████████████████▉            | 1.1MB 565kB/s eta
    62% |████████████████████            | 1.1MB 476kB/s eta
    62% |████████████████████▏           | 1.1MB 404kB/s et
    63% |████████████████████▍           | 1.2MB 417kB/s et
    64% |████████████████████▌           | 1.2MB 350kB/s et
    64% |████████████████████▊           | 1.2MB 324kB/s et
    65% |████████████████████▉           | 1.2MB 323kB/s et
    65% |█████████████████████           | 1.2MB 439kB/s et
    66% |█████████████████████▎          | 1.2MB 439kB/s e
    66% |█████████████████████▍          | 1.2MB 334kB/s e
    67% |█████████████████████▋          | 1.2MB 332kB/s e
    68% |█████████████████████▊          | 1.2MB 368kB/s e
    68% |██████████████████████          | 1.2MB 421kB/s e
    69% |██████████████████████▏         | 1.3MB 411kB/s
    69% |██████████████████████▎         | 1.3MB 504kB/s
    70% |██████████████████████▌         | 1.3MB 433kB/s
    70% |██████████████████████▊         | 1.3MB 433kB/s
    71% |██████████████████████▉         | 1.3MB 439kB/s
    71% |███████████████████████         | 1.3MB 309kB/s
    72% |███████████████████████▏        | 1.3MB 435kB/s
    73% |███████████████████████▍        | 1.3MB 433kB/s
    73% |███████████████████████▋        | 1.3MB 407kB/s
    74% |███████████████████████▊        | 1.4MB 407kB/s
    74% |████████████████████████        | 1.4MB 379kB/s
    75% |████████████████████████▏       | 1.4MB 377kB/
    75% |████████████████████████▎       | 1.4MB 424kB/
    76% |████████████████████████▌       | 1.4MB 343kB/
    77% |████████████████████████▋       | 1.4MB 383kB/
    77% |████████████████████████▉       | 1.4MB 489kB/
    78% |█████████████████████████       | 1.4MB 455kB/
    78% |█████████████████████████▏      | 1.4MB 461kB
    79% |█████████████████████████▍      | 1.4MB 447kB
    79% |█████████████████████████▋      | 1.5MB 451kB
    80% |█████████████████████████▊      | 1.5MB 395kB
    80% |██████████████████████████      | 1.5MB 393kB
    81% |██████████████████████████      | 1.5MB 428kB
    82% |██████████████████████████▎     | 1.5MB 525k
    82% |██████████████████████████▌     | 1.5MB 439k
    83% |██████████████████████████▋     | 1.5MB 533k
    83% |██████████████████████████▉     | 1.5MB 525k
    84% |███████████████████████████     | 1.5MB 525k
    84% |███████████████████████████▏    | 1.5MB 514
    85% |███████████████████████████▍    | 1.6MB 414
    86% |███████████████████████████▌    | 1.6MB 538
    86% |███████████████████████████▊    | 1.6MB 497
    87% |████████████████████████████    | 1.6MB 451
    87% |████████████████████████████    | 1.6MB 465
    88% |████████████████████████████▎   | 1.6MB 53
    88% |████████████████████████████▍   | 1.6MB 52
    89% |████████████████████████████▋   | 1.6MB 46
    89% |████████████████████████████▉   | 1.6MB 46
    90% |█████████████████████████████   | 1.6MB 53
    91% |█████████████████████████████▏  | 1.7MB 5
    91% |█████████████████████████████▍  | 1.7MB 3
    92% |█████████████████████████████▌  | 1.7MB 3
    92% |█████████████████████████████▊  | 1.7MB 4
    93% |█████████████████████████████▉  | 1.7MB 4
    93% |██████████████████████████████  | 1.7MB 4
    94% |██████████████████████████████▎ | 1.7MB
    95% |██████████████████████████████▍ | 1.7MB
    95% |██████████████████████████████▋ | 1.7MB
    96% |██████████████████████████████▊ | 1.8MB
    96% |███████████████████████████████ | 1.8MB
    97% |███████████████████████████████▏| 1.8MB
    97% |███████████████████████████████▎| 1.8MB
    98% |███████████████████████████████▌| 1.8MB
    98% |███████████████████████████████▊| 1.8MB
    99% |███████████████████████████████▉| 1.8MB
    100% |████████████████████████████████| 1.8M
B 171kB/s
Collecting virtualenvwrapper
  Downloading virtualenvwrapper-4.7.2.tar.gz (90kB)
    45% |██████████████▌                 | 40kB 568kB/s eta 0:00:
    56% |██████████████████              | 51kB 506kB/s eta 0:
    67% |█████████████████████▊          | 61kB 596kB/s et
    79% |█████████████████████████▎      | 71kB 530kB/
    90% |█████████████████████████████   | 81kB 561
    100% |████████████████████████████████| 92kB
 529kB/s
Collecting virtualenv-clone (from virtualenvwrapper)
  Downloading virtualenv-clone-0.2.6.tar.gz
Collecting stevedore (from virtualenvwrapper)
  Downloading stevedore-1.25.0-py2.py3-none-any.whl
Requirement already satisfied: six>=1.9.0 in c:\users\administrator\appdata\loca
l\programs\python\python35\lib\site-packages (from stevedore->virtualenvwrapper)

Collecting pbr!=2.1.0,>=2.0.0 (from stevedore->virtualenvwrapper)
  Downloading pbr-3.1.1-py2.py3-none-any.whl (99kB)
    41% |█████████████▏                  | 40kB 538kB/s eta 0:00:0
    51% |████████████████▍               | 51kB 487kB/s eta 0:0
    61% |███████████████████▊            | 61kB 568kB/s eta
    71% |███████████████████████         | 71kB 511kB/s e
    82% |██████████████████████████▎     | 81kB 484kB
    92% |█████████████████████████████▋  | 92kB 53
    100% |████████████████████████████████| 102k
B 471kB/s
Installing collected packages: virtualenv, virtualenv-clone, pbr, stevedore, vir
tualenvwrapper
  Running setup.py install for virtualenv-clone ... done
  Running setup.py install for virtualenvwrapper ... done
Successfully installed pbr-3.1.1 stevedore-1.25.0 virtualenv-15.1.0 virtualenv-c
lone-0.2.6 virtualenvwrapper-4.7.2

E:\ScienceSoft\Python\Django>pip install virtualenvwrapper-win
Collecting virtualenvwrapper-win
  Downloading virtualenvwrapper-win-1.2.1.zip
Requirement already satisfied: virtualenv in c:\users\administrator\appdata\loca
l\programs\python\python35\lib\site-packages (from virtualenvwrapper-win)
Installing collected packages: virtualenvwrapper-win
  Running setup.py install for virtualenvwrapper-win ... done
Successfully installed virtualenvwrapper-win-1.2.1

E:\ScienceSoft\Python\Django>mkvirtualenv ContentManagePro
Using base prefix 'c:\\users\\administrator\\appdata\\local\\programs\\python\\p
ython35'
New python executable in C:\Users\Administrator\Envs\ContentManagePro\Scripts\py
thon.exe
Installing setuptools, pip, wheel...done.

(ContentManagePro) E:\ScienceSoft\Python\Django>mkvirtualenv minicms
Using base prefix 'c:\\users\\administrator\\appdata\\local\\programs\\python\\p
ython35'
New python executable in C:\Users\Administrator\Envs\minicms\Scripts\python.exe
Installing setuptools, pip, wheel...done.

(minicms) E:\ScienceSoft\Python\Django>django-admin.py startproject mincms

(minicms) E:\ScienceSoft\Python\Django>django-admin.py startproject minicms

(minicms) E:\ScienceSoft\Python\Django>cd minicms

(minicms) E:\ScienceSoft\Python\Django\minicms>python manage.py startapp news
Traceback (most recent call last):
  File "manage.py", line 8, in <module>
    from django.core.management import execute_from_command_line
ImportError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 14, in <module>
    import django
ImportError: No module named 'django'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available o
n your PYTHONPATH environment variable? Did you forget to activate a virtual env
ironment?

(minicms) E:\ScienceSoft\Python\Django\minicms>cd..

(minicms) E:\ScienceSoft\Python\Django>env\Scripts\activate
系統(tǒng)找不到指定的路徑。

(minicms) E:\ScienceSoft\Python\Django>cd..

(minicms) E:\ScienceSoft\Python>virtualenv
You must provide a DEST_DIR
Usage: virtualenv [OPTIONS] DEST_DIR

Options:
  --version             show program's version number and exit
  -h, --help            show this help message and exit
  -v, --verbose         Increase verbosity.
  -q, --quiet           Decrease verbosity.
  -p PYTHON_EXE, --python=PYTHON_EXE
                        The Python interpreter to use, e.g.,
                        --python=python2.5 will use the python2.5 interpreter
                        to create the new environment.  The default is the
                        interpreter that virtualenv was installed with (c:\use
                        rs\administrator\appdata\local\programs\python\python3
                        5\python.exe)
  --clear               Clear out the non-root install and start from scratch.
  --no-site-packages    DEPRECATED. Retained only for backward compatibility.
                        Not having access to global site-packages is now the
                        default behavior.
  --system-site-packages
                        Give the virtual environment access to the global
                        site-packages.
  --always-copy         Always copy files rather than symlinking.
  --unzip-setuptools    Unzip Setuptools when installing it.
  --relocatable         Make an EXISTING virtualenv environment relocatable.
                        This fixes up scripts and makes all .pth files
                        relative.
  --no-setuptools       Do not install setuptools in the new virtualenv.
  --no-pip              Do not install pip in the new virtualenv.
  --no-wheel            Do not install wheel in the new virtualenv.
  --extra-search-dir=DIR
                        Directory to look for setuptools/pip distributions in.
                        This option can be used multiple times.
  --download            Download preinstalled packages from PyPI.
  --no-download, --never-download
                        Do not download preinstalled packages from PyPI.
  --prompt=PROMPT       Provides an alternative prompt prefix for this
                        environment.
  --setuptools          DEPRECATED. Retained only for backward compatibility.
                        This option has no effect.
  --distribute          DEPRECATED. Retained only for backward compatibility.
                        This option has no effect.

(minicms) E:\ScienceSoft\Python>virtualenv env
Using base prefix 'c:\\users\\administrator\\appdata\\local\\programs\\python\\p
ython35'
New python executable in E:\ScienceSoft\Python\env\Scripts\python.exe
Installing setuptools, pip, wheel...done.

(minicms) E:\ScienceSoft\Python>cd E:\ScienceSoft\Python\env\Scripts

(minicms) E:\ScienceSoft\Python\env\Scripts>activate.bat

(env) E:\ScienceSoft\Python\env\Scripts>pip install requests
Collecting requests
  Using cached requests-2.18.1-py2.py3-none-any.whl
Collecting certifi>=2017.4.17 (from requests)
  Using cached certifi-2017.4.17-py2.py3-none-any.whl
Collecting chardet<3.1.0,>=3.0.2 (from requests)
  Using cached chardet-3.0.4-py2.py3-none-any.whl
Collecting idna<2.6,>=2.5 (from requests)
  Using cached idna-2.5-py2.py3-none-any.whl
Collecting urllib3<1.22,>=1.21.1 (from requests)
  Using cached urllib3-1.21.1-py2.py3-none-any.whl
Installing collected packages: certifi, chardet, idna, urllib3, requests
Successfully installed certifi-2017.4.17 chardet-3.0.4 idna-2.5 requests-2.18.1
urllib3-1.21.1

(env) E:\ScienceSoft\Python\env\Scripts>mkvirtualenv minicms
Using base prefix 'c:\\users\\administrator\\appdata\\local\\programs\\python\\p
ython35'
New python executable in C:\Users\Administrator\Envs\minicms\Scripts\python.exe
Installing setuptools, pip, wheel...done.

(minicms) E:\ScienceSoft\Python\env\Scripts>

導入數(shù)據(jù):

create_demo_records.py:

# 為數(shù)據(jù)庫添加一些記錄

from minicms.wsgi import *
from news.models import Column, Article

def main():

    columns_urls = [

        ('娛樂新聞', 'Play'),
        ('旅游新聞', 'tourist'),
        ('美食新聞', 'Food'),


    ]

    for column_name, url in columns_urls:

        c = Column.objects.get_or_create(name=column_name, slug=url)[0]

        # 創(chuàng)建10篇新聞

        for i in range(1, 11):
            article = Article.objects.get_or_create(

                title='{}_{}'.format(column_name, i),
                slug='article_{}'.format(i),
                content='新聞詳細內(nèi)容: {} {}'.format(column_name, i)


                )[0]

            article.column.add(c)

if __name__ == '__main__':

    main()
    print("Done!")

假設這個文件被保存為 create_demo_records.py (和 manage.py 放在一塊,同一個文件夾下)

運行腳本 導入數(shù)據(jù):

1
python create_demo_records.py
Done!

終端上顯示一個 Done! 就這樣 Duang 的一下,數(shù)據(jù)就導進去了!
Django 開發(fā)內(nèi)容管理系統(tǒng)(第二天)——后臺
完善后臺的功能,在后臺添加,編輯,刪除數(shù)據(jù)

更改 news/admin.py:

from django.contrib import admin

# Register your models here.
from .modelsimport Column, Article

class ColumnAdmin(admin.ModelAdmin):

   list_display = {'name', 'slug', 'intro',}
class ArticleAdmin(admin.ModelAdmin):
   list_display = ('title', 'slug', 'author', 'pub_date', 'update_time')


admin.site.register(Column, ColumnAdmin)
admin.site.register(Article, ArticleAdmin)

創(chuàng)建一個超級管理員(如果你沒有后臺帳戶和密碼的話)

修改models.py:
    pub_date = models.DateTimeField('發(fā)表時間', auto_now_add=True, editable=True)
    
    update_time = models.DateTimeField('更新時間', auto_now=True, null=True)
E:\ScienceSoft\Python\env\minicms>python manage.py makemigrations news
You are trying to add the field 'pub_date' with 'auto_now_add=True' to article w
ithout a default; the database needs something to populate existing rows.

 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
Select an option:
[default: timezone.now] >>>
# 按Enter,這樣就生成如下文件
# 生成了一個對表進行更改的 py 文件在 news/migrations 文件夾中
Migrations for 'news':
  news\migrations\0002_auto_20170724_1626.py
    - Add field pub_date to article
    - Add field update_time to article
# 我們要執(zhí)行更改
E:\ScienceSoft\Python\env\minicms> python manage.py migrate news
Operations to perform:
  Apply all migrations: news
Running migrations:
  Applying news.0002_auto_20170724_1626... OK

E:\ScienceSoft\Python\env\minicms>
創(chuàng)建一個超級管理員(如果你沒有后臺帳戶和密碼的話)
無用戶名(默認用戶名administrator)+密碼L1234567
python manage.py createsuperuser
E:\ScienceSoft\Python\env\minicms>python manage.py runserve
Performing system checks...
這里我們打開開發(fā)服務器,訪問后臺網(wǎng)址,就可以看到:
System check identified no issues (0 silenced).
July 24, 2017 - 16:29:36
Django version 1.11.3, using settings 'minicms.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
http://127.0.0.1:8000/admin用瀏覽器打開
image.png
image.png

點擊欄目——可以查看后臺欄目列表

image.png
image.png

我們已經(jīng)可以在后臺進行更改和保存文章了,但是在編輯新聞的時候是不是覺得不爽,沒有一個編輯器,我們下面來集成百度的Ueditor 到我們的系統(tǒng):

集成 DjangoUeditor 編輯器:安裝 DjangoUeditor 包
1.把里面的 DjangoUeditor-master 中的 DjangoUeditor 文件夾放到 news 同一級目錄,如圖所求:

2.在 minicms/settings.py 中加入 DjangoUeditor 這個應用

3.這一段是后來加的,github上沒有
我們已經(jīng)可以在后臺進行更改和保存文章了,但是在編輯新聞的時候是不是覺得不爽,沒有一個編輯器,我們下面來集成百度的Ueditor 到我們的系統(tǒng):
為了讓上傳的圖片,文件可以在本地調(diào)試的時候可以正常顯示,下載,

在 minicms/settings.py 設置 static 和 media

經(jīng)過上述修改后,再次打開,發(fā)現(xiàn),已經(jīng)可以使用了:


image.png

后臺的功能就講到這里,大家可以后期自己再進行完善。

提示:其實這里有個 bug, 不同欄目,不同文章網(wǎng)址可以是一樣的,先不管這個,我們稍后會修復它

下面我們來完善這三個視圖函數(shù)(這里為了告訴大家如何做,我們不用通用視圖,因為通用視圖都幫大家做好了,學不到什么東西)
首頁 index 欄目 column 文章詳情 article
代碼如下:
minicms/new/views.py:


上面是一個大致框架,我們馬上完善它,大家看一下參數(shù)是如何傳遞的,可以打開開發(fā)服務器 python manage.py runserver
訪問比如:http://127.0.0.1:8002/column/tech/ (注意端口,改成你自己的)會得到:

image.png
image.png

我們發(fā)現(xiàn) slug 已經(jīng)被正確傳遞到了 views.py 中的視圖函數(shù),我們在 views.py 中可以用 slug 檢索出相應的欄目或文章。

至此,我們已經(jīng)知道欄目網(wǎng)址和文章網(wǎng)址的規(guī)則,我們現(xiàn)在用代碼來生成相關的網(wǎng)址,我們運行 python manage.py shell 進入有項目環(huán)境的終端

In [2]: # column

In [3]: reverse('column', args=('tech',))
Out[3]: '/column/tech/'

In [4]: reverse('column', args=('play',))
Out[4]: '/column/play/'

In [5]: reverse('column', args=('Play',))
Out[5]: '/column/Play/'

In [6]: # article

In [7]: reverse('article', args=('article_slug',))
Out[7]: '/news/article_slug/'

In [8]: reverse('article', args=('windows_7',))
Out[8]: '/news/windows_7/'

我們修改 models.py ,將獲取網(wǎng)址的功能寫成一個函數(shù) get_absolute_url ,然后在模板或其它腳本中調(diào)用。

后臺默認也會調(diào)用這個函數(shù),可以理解成一個約定俗成的名稱。
models.py:

from __future__ import unicode_literals
# import os,django
# os.environ.setdefault("DJANGO_SETTINGS_MODULE", "minicms.settings")# project_name 項目名稱
# django.setup()
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
from DjangoUeditor.models import UEditorField
# from widgets import UEditorWidget,AdminUEditorWidget
# from django.forms.widgets import Widget
from django.core.urlresolvers import reverse
#from django.forms.widgets import *
# Create your models here.
class Column(models.Model):

    name = models.CharField('欄目名稱', max_length=256)

    slug = models.CharField('欄目網(wǎng)址', max_length=256, db_index=True)

    intro = models.TextField('欄目簡介', default='')

    def __str__(self):

        return self.name
# 將獲取網(wǎng)址的功能寫成一個函數(shù) get_absolute_url ,然后在模板或其它腳本中調(diào)用
    def get_absolute_url(self):

        return reverse('column', args=(self.slug,))

    class Meta:

        verbose_name = '欄目'

        verbose_name_plural = '欄目'

        ordering = ['name'] # 按照哪個欄目排序

class Article(models.Model):

    column = models.ManyToManyField(Column, verbose_name='歸屬欄目')

    title = models.CharField('標題', max_length=256)

    slug = models.CharField('網(wǎng)址', max_length=256, db_index=True)

    author = models.ForeignKey('auth.user', blank=True, null=True, verbose_name='作者')

    # content = models.TextField('內(nèi)容', default='', blank=True)
    #僅修改 content 字段
    content = UEditorField('內(nèi)容', height=300, width=1000,

        default=u'', blank=True, imagePath="uploads/images/",
        toolbars='besttome', filePath='uploads/files/'
        )

    published = models.BooleanField('正式發(fā)布', default=True)

    pub_date = models.DateTimeField('發(fā)表時間', auto_now_add=True, editable=True)
    
    update_time = models.DateTimeField('更新時間', auto_now=True, null=True)

    def __str__(self):

        return self.title
    def get_absolute_url(self):

        return reverse('article', args(self.slug,))
# 注意 args 參數(shù)為元組,寫 args=(self.slug) 這樣是錯的,
# 注意后面有一個逗號 args=(self.slug,)
    class Meta:

        verbose_name = '教程'

        verbose_name_plural = '教程'



注意 args 參數(shù)為元組,寫 args=(self.slug) 這樣是錯的,注意后面有一個逗號 args=(self.slug,)
AttributeError Traceback (most recent call last)
<ipython-input-16-c52e47ff1d35> in <module>()
----> 1 c.get_absolute_url()

AttributeError: 'Column' object has no attribute 'get_absolute_url'
原因:需要我們重新進入解釋器和注意縮進
我們再次進入 終端 python manage.py shell

In [1]: from news.models import Column, Article

In [2]: c = Column.objects.all()[0]

In [3]: c.get_absolute_url()
Out[3]: '/column/sports/'

In [4]: a = Article.objects.all()[0]

In [5]: a.get_absolute_url()
Out[5]: '/news/article_1/'

In [6]:


我們可以看到這樣已經(jīng)可以獲取到文章或者欄目的網(wǎng)址了,下面我們在模板中顯示它們。
相關模板文件

我們先寫一個 base.html 所有的其它模板都繼承它,由于 base.html 不屬于某一個 app,它是整個項目共用的,我們建立一個專門的 模塊文件夾來放它樣的文件。

比如還有其它的 baidu#html ,把百度統(tǒng)計的代碼放進去來統(tǒng)計訪問情況。

我們修改 settings.py,添加一個模板目錄 項目下 templates 文件夾。
項目目錄下 建一個 templates 文件夾,里面寫一個 base.html
修改 settings.py:

 'DIRS': [os.path.join(BASE_DIR, 'templates')], #修改了這一行

項目目錄下 建一個 templates 文件夾,里面寫一個 base.html

templates/base.html 模板文件:

<!DOCTYPE html>
<html>
   <head>
    <meta charset="utf-8">
    <title>{% blocktitle %}歡迎光臨{% endblock title %} - 自強學堂</title>


    {% block css %}

    {% endblock css %}

    {% block js %}

    {% endblock js %}

    </head>

    <body>
    {% block content %}
       <h1> 俊 的 網(wǎng)頁</h1>

    {% endblockcontent %}

    {% include "baidu#html" %}
    </body>
</html>

templates/baidu#html:

<!-- 這里放統(tǒng)計的代碼 -->


<!-- 百度統(tǒng)計 begin -->

<div style="display:none" hidden>

<script type="text/javascript">

var _bdhmProtocol = (("https:" == document.location.protocol) ? "http://" : "http://");

document.write(unescape("%3Cscript src='" + _bdhmProtocol +  "#/h.js%3Fab8b04b0bf640ac196520db1cd029664' type='text/javascript'%3E%3C/script%3E"));


</script>
    
</div>
<!-- 百度統(tǒng)計 end-->


視圖中檢索結(jié)果,渲染到模板中顯示出來

我們改寫視圖函數(shù),查詢數(shù)據(jù)庫,得到相關的內(nèi)容:
views.py:

# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse


def index(request):
    return HttpResponse(u'歡迎來 PHPERZ 學習Django')


def column_detail(request, column_slug):
# 改寫視圖函數(shù),查詢數(shù)據(jù)庫,得到相關的內(nèi)容
    column = Column.objects.get(slug=column_slug)
    return HttpResponse('column slug: ' + column_slug)


def article_detail(request, article_slug):
    article = Article.objects.get(slug=article_slug)
    return render(reuest, 'news/article.html', {'article': article})
 # return HttpResponse('article slug: ' + article_slug)

在 news 下新建 templates 文件夾,再在 templates 下新建 news 文件夾,我們來寫兩個模板文件:

欄目模板,視圖傳遞過來了一個 column object

<!-- 欄目模板,視圖傳遞過來了一個 column object-->

{% extends "base.html" %}

{% block title %}

{{ colimn.title }}
{% endblock title %}


{% block content %}

欄目簡介: {{ column.intro }}
欄目文章列表:
還需要完善
{% endblock content %}

文章模板,視圖傳遞過來了一個 article object

news/templates/news/article.html (或者 項目下的 templates/news/article.html)

<!-- 文章模板,視圖傳遞過來了一個 article object -->

{% extends "base.html" %}

{% block title %}
{{ article.title }}

{% endblock title %}


{% block content %}
<h1> 文章標題: {{ article.title }}</h1>
<div id="main">
    

    {{ article.content }}
    
</div>
{% endblock content %}

我們先在首頁顯示所有欄目及鏈接:

news/views.py:

def index(request):
    # 先在首頁顯示所有欄目及鏈接
    columns = Column.objects.all()
    return render(request, 'index.html', {'columns': columns})
    #return HttpResponse(u'歡迎來 PHPERZ 學習Django')

項目下 templates/index.html:


們再次在終端測試,安裝 bpython,會提示相關的屬性和方法

1
python manage.py shell
下面是測試結(jié)果
image.png
In [6]: from news.models import Column

In [7]: c = Column.objects.all()[0]

In [8]: c
Out[8]: <Column: 體育新聞>

In [9]: c.article_set.all()
Out[9]: <QuerySet [<Article: 體育新聞_1>, <Article: 體育新聞_2>, <Article: 體育
新聞_3>, <Article: 體育新聞_4>, <Article: 體育新聞_5>, <Article: 體育新聞_6>, <A
rticle: 體育新聞_7>, <Article: 體育新聞_8>, <Article: 體育新聞_9>, <Article: 體
育新聞_10>]>

我們發(fā)現(xiàn)用 column.article_set.all() 方法可以獲取欄目相關的文章。

我們改一下 news/templates/news/column.html
Django 開發(fā)內(nèi)容管理系統(tǒng)(第三天)
需要添加一個欄目,才可以對其修改一些欄目為首頁和導航顯示:

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

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

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