Django + uwsgi + nginx + bootstrap 創(chuàng)建自己的博客 -- 7.Template

Template初探

到目前為止我們只是簡(jiǎn)單的將后端數(shù)據(jù)顯示到頁面上, 沒有涉及到HTML代碼, 而優(yōu)雅的網(wǎng)站總算通過CSS+HTML, 甚至還有強(qiáng)大的JS的支持.

在這個(gè)教程中要打造一個(gè)Blog, 所以我們?cè)O(shè)置一個(gè)Blog界面, 原本打算使用Bootstrap作為前段的工具, 不過經(jīng)過@游逸的建議, 使用了更加輕量級(jí)的Pure, 同樣是響應(yīng)式頁面設(shè)置, 這也將是未來的主流吧..

在my_blog下添加文件名, 文件夾名為templates

mkdir templates
#看到當(dāng)前文件構(gòu)成
my_blog
├── article
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-34.pyc
│   │   ├── admin.cpython-34.pyc
│   │   ├── models.cpython-34.pyc
│   │   └── views.cpython-34.pyc
│   ├── admin.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       ├── 0001_initial.cpython-34.pyc
│   │       └── __init__.cpython-34.pyc
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── my_blog
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-34.pyc
│   │   ├── settings.cpython-34.pyc
│   │   ├── urls.cpython-34.pyc
│   │   └── wsgi.cpython-34.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── templates

在my_blog/my_blog/setting.py下設(shè)置templates的位置

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates').replace('\\', '/'),
    )

1.7/1.8版本Django已經(jīng)修改的template添加形式

#嘗試這種寫法
TEMPLATE_PATH = os.path.join(BASE_DIR, 'templates')
TEMPLATE_DIRS = (
    TEMPLATE_PATH,
)

第一個(gè)template

templates/test.html簡(jiǎn)單第一個(gè) template html文件

<!--在test.html文件夾下添加-->
<!DOCTYPE html>
<html>
    <head>
        <title>Just test template</title>
        <style>
            body {
               background-color: red;
            }
            em {
                color: LightSeaGreen;
            }
        </style>
    </head>
    <body>
        <h1>Hello World!</h1>
        <strong>{{ current_time }}</strong>
    </body>
</html>
其中{{ current_time }}是Django Template中變量的表示方式

意思是告知項(xiàng)目templates文件夾在項(xiàng)目根目錄下

在article/view.py中添加一個(gè)函數(shù)邏輯

from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
from datetime import datetime

# Create your views here.
def home(request):
    return HttpResponse("Hello World, Django")

def detail(request, my_args):
    post = Article.objects.all()[int(my_args)]
    str = ("title = %s, category = %s, date_time = %s, content = %s" 
        % (post.title, post.category, post.date_time, post.content))
    return HttpResponse(str)

def test(request) :
    return render(request, 'test.html', {'current_time': datetime.now()})

render()函數(shù)中第一個(gè)參數(shù)是request 對(duì)象, 第二個(gè)參數(shù)是一個(gè)模板名稱撬槽,第三個(gè)是一個(gè)字典類型的可選參數(shù). 它將返回一個(gè)包含有給定模板根據(jù)給定的上下文渲染結(jié)果的 HttpResponse對(duì)象度液。

然后設(shè)置對(duì)應(yīng)的url在my_blog/urls.py下

    url(r'^test/$', 'article.views.test'),

重新啟動(dòng)服務(wù)器python manage.py runserver, 然后在瀏覽器中輸入http://127.0.0.1:8000/test/, 可以看到

Mou icon

正式編寫template

在template文件夾下增加base.html, 并在其中增加如下代碼

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="A layout example that shows off a blog page with a list of posts.">

    <title>Andrew Liu Blog</title>
    <link rel="stylesheet" >
    <link rel="stylesheet" >
    <link rel="stylesheet" >
</head>
<body>
<div id="layout" class="pure-g">
    <div class="sidebar pure-u-1 pure-u-md-1-4">
        <div class="header">
            <h1 class="brand-title">Andrew Liu Blog</h1>
            <h2 class="brand-tagline">雪憶 - Snow Memory</h2>
            <nav class="nav">
                <ul class="nav-list">
                    <li class="nav-item">
                        <a class="pure-button" >Github</a>
                    </li>
                    <li class="nav-item">
                        <a class="pure-button" >Weibo</a>
                    </li>
                </ul>
            </nav>
        </div>
    </div>

    <div class="content pure-u-1 pure-u-md-3-4">
        <div>
            {% block content %}
            {% endblock %}
            <div class="footer">
                <div class="pure-menu pure-menu-horizontal pure-menu-open">
                    <ul>
                        <li><a >About Me</a></li>
                        <li><a >Twitter</a></li>
                        <li><a >GitHub</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>

上面這段html編寫的頁面是一個(gè)模板, 其中{% block content %} {% endblock %}字段用來被其他繼承這個(gè)基類模板進(jìn)行重寫

我們繼續(xù)在templates文件夾下添加home.html文件

{% extends "base.html" %}

{% block content %}
<div class="posts">
    {% for post in post_list %}
        <section class="post">
            <header class="post-header">
                <h2 class="post-title">{{ post.title }}</h2>

                    <p class="post-meta">
                        Time:  <a class="post-author" href="#">{{ post.date_time }}</a> <a class="post-category post-category-js" href="#">{{ post.category }}</a>
                    </p>
            </header>

                <div class="post-description">
                    <p>
                        {{ post.content }}
                    </p>
                </div>
        </section>
    {% endfor %}
</div><!-- /.blog-post -->
{% endblock %}
其中
- {% for <element> in <list> %}與{% endfor %}成對(duì)存在, 這是template中提供的for循環(huán)tag
- {% if <elemtnt> %} {% else %} {% endif %}是template中提供的if語句tag
- template中還提供了一些過濾器

然后修改my_blog/article/view.py, 并刪除test.html

# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from article.models import Article
from datetime import datetime

# Create your views here.
def home(request):
    post_list = Article.objects.all()  #獲取全部的Article對(duì)象
    return render(request, 'home.html', {'post_list' : post_list})

修改my_blog/my_blog/urls.py

from django.conf.urls import patterns, include, url
from django.contrib import admin

urlpatterns = patterns('',
    # Examples:
    # url(r'^$', 'my_blog.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'article.views.home'),
)

現(xiàn)在重新打開http://127.0.0.1:8000/, 發(fā)現(xiàn)Blog的整理框架已經(jīng)基本完成, 到現(xiàn)在我們已經(jīng)了解了一些Django的基本知識(shí), 搭建了簡(jiǎn)單地Blog框架, 剩下的就是給Blog添加功能

Mou icon

查看當(dāng)前整個(gè)程序的目錄結(jié)構(gòu)

my_blog
├── article
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-34.pyc
│   │   ├── admin.cpython-34.pyc
│   │   ├── models.cpython-34.pyc
│   │   └── views.cpython-34.pyc
│   ├── admin.py
│   ├── migrations
│   │   ├── 0001_initial.py
│   │   ├── __init__.py
│   │   └── __pycache__
│   │       ├── 0001_initial.cpython-34.pyc
│   │       └── __init__.cpython-34.pyc
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── manage.py
├── my_blog
│   ├── __init__.py
│   ├── __pycache__
│   │   ├── __init__.cpython-34.pyc
│   │   ├── settings.cpython-34.pyc
│   │   ├── urls.cpython-34.pyc
│   │   └── wsgi.cpython-34.pyc
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
└── templates
    ├── base.html
    └── home.html

將代碼上傳到Github

在github中新建倉庫my_blog_tutorial, 填寫簡(jiǎn)單的描述

#查看當(dāng)前目錄位置
$ pwd
/Users/andrew_liu/Python/Django/my_blog

#在項(xiàng)目的根目錄下初始化git
git init
Initialized empty Git repository in/Users/andrew_liu/Python/Django/my_blog/.git/

#添加遠(yuǎn)程github
$ git remote add blog git@github.com:Andrew-liu/my_blog_tutorial.git
在根目錄下增加`.gitignore'和'LICENSE'和'README.md'文件

#添加所有文件
$ git add .

#查看當(dāng)前狀態(tài)
$ git status

#commit操作
$ git commit -m "django tutorial init"

#上傳github
$ git push -u blog master
Counting objects: 23, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (22/22), done.
Writing objects: 100% (23/23), 19.56 KiB | 0 bytes/s, done.
Total 23 (delta 1), reused 0 (delta 0)
To git@github.com:Andrew-liu/my_blog_tutorial.git
 * [new branch]      master -> master
Branch master set up to track remote branch master from blog.
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市蛮粮,隨后出現(xiàn)的幾起案子丧靡,更是在濱河造成了極大的恐慌饮戳,老刑警劉巖折剃,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異绪抛,居然都是意外死亡资铡,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門幢码,熙熙樓的掌柜王于貴愁眉苦臉地迎上來笤休,“玉大人,你說我怎么就攤上這事症副〉暄牛” “怎么了?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵贞铣,是天一觀的道長(zhǎng)闹啦。 經(jīng)常有香客問我,道長(zhǎng)辕坝,這世上最難降的妖魔是什么窍奋? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮酱畅,結(jié)果婚禮上琳袄,老公的妹妹穿的比我還像新娘。我一直安慰自己纺酸,他們只是感情好窖逗,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著餐蔬,像睡著了一般碎紊。 火紅的嫁衣襯著肌膚如雪佑附。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天仗考,我揣著相機(jī)與錄音音同,去河邊找鬼。 笑死痴鳄,一個(gè)胖子當(dāng)著我的面吹牛瘟斜,可吹牛的內(nèi)容都是我干的缸夹。 我是一名探鬼主播痪寻,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼虽惭!你這毒婦竟也來了橡类?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤芽唇,失蹤者是張志新(化名)和其女友劉穎顾画,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體匆笤,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡研侣,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了炮捧。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片庶诡。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖咆课,靈堂內(nèi)的尸體忽然破棺而出末誓,到底是詐尸還是另有隱情,我是刑警寧澤书蚪,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布喇澡,位于F島的核電站,受9級(jí)特大地震影響殊校,放射性物質(zhì)發(fā)生泄漏晴玖。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一为流、第九天 我趴在偏房一處隱蔽的房頂上張望呕屎。 院中可真熱鬧,春花似錦艺谆、人聲如沸榨惰。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽琅催。三九已至居凶,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間藤抡,已是汗流浹背侠碧。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留缠黍,地道東北人弄兜。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓博投,卻偏偏與公主長(zhǎng)得像蚜印,于是被迫代替她去往敵國和親狱窘。 傳聞我的和親對(duì)象是個(gè)殘疾皇子膨蛮,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容