1、为什么要写这个文章

由于《Django简易博客搭建教程》是基于python3.4.1+django1.7.1,在python已经进入3.6的时代,以及最重要的,django已经进入2的时代下,重新把书中的代码及时更新一下还是很有必要的。另附github:

https://github.com/DachuanZhao/learnDjango

2、代码

(1)无

(2)在这里我并没有使用虚拟环境和bootstrap

pip3 install Django
apt-get install git

(3)

django-admin.py startproject my_blog
cd my_blog
python3 manage.py startapp article
tree ../my_blog
#返回
#######################################################
../my_blog/
├── article
│   ├── admin.py
│   ├── apps.py
│   ├── __init__.py
│   ├── migrations
│   │   └── __init__.py
│   ├── models.py
│   ├── tests.py
│   └── views.py
├── db.sqlite3
├── manage.py
└── my_blog
    ├── __init__.py
    ├── __pycache__
    │   ├── __init__.cpython-35.pyc
    │   ├── settings.cpython-35.pyc
    │   ├── urls.cpython-35.pyc
    │   └── wsgi.cpython-35.pyc
    ├── settings.py
    ├── urls.py
    └── wsgi.py
#######################################################
python3 manage.py runserver
#返回
#######################################################
Performing system checks...

System check identified no issues (0 silenced).

You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.

January 25, 2018 - 09:33:22
Django version 2.0.1, using settings 'my_blog.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
#######################################################
python3 manage.py migrate
python3 manage.py runserver

(4)创建并修改my_blog/article/models.py中的内容如下:

from django.db import models

# Create your models here.
class Article(models.Model):
    title = models.CharField(max_length = 100)
    category = models.CharField(max_length = 50, blank = True)
    date_time = models.DateTimeField(auto_now_add = True) #the date of the blog
    content = models.TextField(blank = True,null = True) #the text of the blog

    def __unicode__(self):
        return self.title

    class Meta:#descending order by time
        ordering = ['-date_time']

之后修改my_blog/my_blog/settings.py 为

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'article'
]

并运行

python3 ./my_blog/manage.py migrate
python3 ./my_blog/manage.py makemigrations
python3 ./my_blog/manage.py migrate
python3 ./my_blog/manage.py shell

>>> from article.models import Article

>>> Article.objects.create(title = 'Hello World',category = 'Python3.5.3',content = 'let_s add a new data to the database')
<Article: Article object (1)>

>>> Article.objects.create(title = 'Learn Django Blog',category = 'Python3.5.3',content = 'create a simple blog by python3.5.3 and Django2')
<Article: Article object (2)>

>>> Article.objects.all()
<QuerySet [<Article: Article object (2)>, <Article: Article object (1)>]>

>>> Article.objects.get(id=1)
<Article: Article object (1)>

>>> first = Article.objects.get(id = 1)

>>> first.title
'Hello World'

>>> first.date_time
datetime.datetime(2018, 2, 1, 7, 57, 44, 409015, tzinfo=<UTC>)

>>> first.content
'let_s add a new data to the database'

>>> first.category
'Python3.5.3'

>>> first.content
'let_s add a new data to the database'


(5)修改my_blog/article/admin.py如下

from django.contrib import admin

# Register your models here.
from article.models import Article
admin.site.register(Article)


(6)

修改my_blog/my_blog/urls.py如下:

from django.contrib import admin
from django.urls import path,re_path,include
from article.views import home,detail
urlpatterns = [
    path('admin/', admin.site.urls),
    re_path(r'^$',home),
    re_path(r'^(?P<my_args>\d+)/$',detail,name = 'detail'),
]

修改my_blog/article/views.py如下:

from django.shortcuts import render

# Create your views here.
from django.http import HttpResponse
from article.models import Article

def home(request):
    return HttpResponse("Hello World,Django")

def detail(request,my_args):
    post = Article.objects.all()[int(my_args)]
    my_str = ("title = %s, category = %s, date_time = %s, content = %s" \
            % (post.title,post.category,post.date_time,post.content))
    #return HttpResponse("You're looking at my_args %s." % my_args)
    return HttpResponse(my_str)

增加主机IP到my_blog/my_blog/settings.py的ALLOWED_HOSTS,以便局域网其他主机能够访问

ALLOWED_HOSTS = ['192.168.2.11']


(7)+(9)markdown

安装markdown

pip3 install markdown

my_blog/article/templatetags/custom_markdown.py

# -*- coding: utf-8 -*-

import markdown

from django import template
from django.template.defaultfilters import stringfilter
from django.utils.encoding import force_text
from django.utils.safestring import mark_safe

register = template.Library()


@register.filter(is_safe=True)  #register template filter
@stringfilter  #set the parameter's name
def custom_markdown(value):
    #extensions = ["nl2br", ]

    return mark_safe(markdown.markdown(value,
        extensions = ['markdown.extensions.fenced_code', 'markdown.extensions.codehilite'],
                                       safe_mode=True,
                                       enable_attributes=False))
    # return mark_safe(markdown2.markdown(force_text(value),
       # extras=["fenced-code-blocks", "cuddled-lists", "metadata", "tables", "spoiler"]))roo

my_blog/templates/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" href="http://yui.yahooapis.com/pure/0.5.0/pure-min.css">
    <link rel="stylesheet" href="http://yui.yahooapis.com/pure/0.5.0/grids-responsive-min.css">
    <link rel="stylesheet" href="http://picturebag.qiniudn.com/blog.css">
</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" href="https://github.com/Andrew-liu">
                                Github</a>
                        </li>
                        <li class="nav-item">
                            <a class="pure-button" href="http://weibo.com/dinosaurliu"> Weibo</a>
                        </li>
                    </ul>
                </nav>
            </div>
        </div>
        <div class="content pure-u-1 pure-u-md-3-4">
            <div>
                <div class="footer">
                    <div class="pure-menu pure-menu-horizontal pure-menu-open">
                        <ul>
                            <li><a href="http://andrewliu.tk/about/"> About Me</a>
                            </li>
                            <li><a href="http://twitter.com/yuilibrary/"> Twitter</a>
                            </li>
                            <li><a href="http://github.com/yahoo/pure/"> GitHub</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>

</html>

my_blog/templates/home.html

{% extends "base.html" %} 
{% load custom_markdown %}
{% block content %}
<div class="posts">
    {% for post in post_list %}
    <section class="post">
        <header class="post-header">
            <h2 class="post-title">
                <a href="{% url 'detail' id=post.id %}">{{ post.title }}</a>
            </h2>

            <p class="post-meta">
                Time:
                <a class="post-author" href="#">{{ post.date_time |date:'Y M d'}}</a>&nbsp&nbsp Category:
                <a class="post-category post-category-pure" href="{% url 'search_tag' tag=post.category %}">{{ post.category|title }}</a>&nbsp&nbsp Tag: {% for tag in post.tag.all %}
                <a class="post-category post-category-pure" href="#">{{ tag }}</a>
                {% endfor %}
            </p>
        </header>

        <div class="post-description">
            <p>
                {{ post.content|custom_markdown|truncatewords_html:100 }}
            </p>
        </div>
        <a class="pure-button" href="{% url 'detail' id=post.id %}">Read More >>> </a>
    </section>
    {% endfor %} {% if post_list.object_list and post_list.paginator.num_pages > 1 %}
    <div>
        <ul class="pager">
            {% if post_list.has_previous %}
            <li>
                <a href="?page={{ post_list.previous_page_number }}">上一页</a>
            </li>
            {% endif %} {% if post_list.has_next %}
            <li>
                <a href="?page={{ post_list.next_page_number }}">下一页</a>
            </li>
            {% endif %}
        </ul>
    </div>
    {% endif %}
</div>
<!-- /.blog-post -->
{% endblock %}