鍍金池/ 教程/ Python/ Template
更上一層樓
歸檔, AboutMe和標簽分類
動態(tài)URL
Django簡介
Models
項目與APP
Template
開發(fā)環(huán)境和Django安裝
多說,markdown和代碼高亮
Admin
Views和URL
搜索和ReadMore
RSS和分頁

Template

Template初探

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

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

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

    mkdir templates
    #看到當前文件構(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('\', '/'),
        )

意思是告知項目templates文件夾在項目根目錄下

第一個template

templates/test.html簡單第一個 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中變量的表示方式

在article/view.py中添加一個函數(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ù)中第一個參數(shù)是request 對象, 第二個參數(shù)是一個模板名稱,第三個是一個字典類型的可選參數(shù). 它將返回一個包含有給定模板根據(jù)給定的上下文渲染結(jié)果的 HttpResponse對象。

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

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

重新啟動服務(wù)器python manage.py runserver, 然后在瀏覽器中輸入, 可以看到

http://wiki.jikexueyuan.com/project/django-set-up-blog/images/66.png" alt="test" />

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

正式編寫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編寫的頁面是一個模板, 其中{% block content %} {% endblock %}字段用來被其他繼承這個基類模板進行重寫

我們繼續(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 in %}與{% endfor %}成對存在, 這是template中提供的for循環(huán)tag
  • {% if %} {% 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對象
        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的基本知識, 搭建了簡單地Blog框架, 剩下的就是給Blog添加功能

http://wiki.jikexueyuan.com/project/django-set-up-blog/images/67.png" alt="基本框架" />

查看當前整個程序的目錄結(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, 填寫簡單的描述

    #查看當前目錄位置
    $ pwd
    /Users/andrew_liu/Python/Django/my_blog

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

    #添加遠程github
    $ git remote add blog git@github.com:Andrew-liu/my_blog_tutorial.git

在根目錄下增加`.gitignore'和'LICENSE'和'README.md'文件

    #添加所有文件
    $ git add .

    #查看當前狀態(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.
上一篇:RSS和分頁