Django_GO01

Django 起航

环境配置:ubuntu

apt install :python, python-pip, openssh-server, vsftpd, git, tree

pip install: virtualenv, pytz

学习书籍:Django架站的16堂课

First Go

使用virtualenv创建虚拟环境

terminal:

1
2
3
4
5
6
7
8
9
10
11
12
13
virtualenv Venv
source Venv/bin/activate
pip install django
django-admin startproject myweb
cd myweb
git remote add origin https://github.com/Hu-chi/myweb
git pull origin master
git add .
git commit -m 'first remote'
git push origin master
git freeze > requirements.txt #把使用的套件更新一份记录在requirements.txt文本文件中
git add .
git push origin master

换一台机子的话:

1
2
3
git clone https://github.com/Hu-chi/myweb
cd myweb
pip install -r 'requirements.txt'

创建框架(virtualenv下):

1
2
python manage.py startapp mainsite
tree

初次运行:

1
python manage.py runserver

File parse

  • manage.py :是管理网站配置的文件,一般不会修改,只负责执行指令

    myweb中的一些重要配置文件:

    • wsgi.py :是和虚拟主机中网页服务器(如Apache)沟通的接口
    • urls.py:设置每一个URL的网址对应的函数以及对应的方式,创建新页面时编辑的文件
    • settings.py:系统设计的位置,进行新建网站所要设置的操作

真正网站所要运行的所有逻辑都是在使用startapp mainsite创建出来的APP文件中。可以让网站的每一个主要功能成为单独的一个模块。符合reuse的概念。

编辑settings.py,增加mainsite模块:

1
2
3
4
5
6
7
8
9
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'mainsite',
]

修改时区:

1
2
LANGUAGE_CODE = 'zh-Hans'
TIME_ZONE = 'Asia/Beijing'

回去配置SQLite存储数据库。

terminal:

1
2
cd ..
python manage.py migrate

会产生一个db.sqlite3文件。

数据表

数据库是以MODEL方式来操作的。以定义一个数据类来作为一个数据表。省去了人在不同数据库操作细节上的精力和时间。

修改mainsite/models.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models
from django.utils import timezone

class Post(models.Model):
title = models.CharField(max_length=200)
slug = models.CharField(max_length=200)
body = models.TextField()
pub_date = models.DateTimeField(default=timezone.now)

class Meta:
ordering = ('-pub_date',)

def __unicode__(self):
return self.title

执行terminal:

1
2
python manage.py makemigrations mainsite
python manage.py migrate

使用python manage.py createsuperuser创建一个管理员账号。

修改mainsite/admin.py:

1
2
3
4
5
6
7
8
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.contrib import admin
from .models import Post
# Register your models here.

admin.site.register(Post)

runserver一下可以看见有数据库管理页面,登录。

post中自行添加并保存。增加了6个。。。

admin.py增加代码:

1
2
3
4
5
6
# Register your models here.

class PostAdmin(admin.ModelAdmin):
list_display = ('title', 'slug', 'pub_date')

admin.site.register(Post, PostAdmin)

读取数据库中的内容

根据Django中MTV架构。为了把数据抽象化,把数据的存取显示分为Model, Template, View。分别对应models.py, template文件, views.py等文件。

models.py用类class来定义了要存取的数据模型。存取数据则是在View,在views.py中处理。显示输出则交给Template处理。

修改mainsite/view.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
# Create your views here

def homepage(request):
posts = Post.objects.all()
post_lists = list()
for count, post in enumerate(posts):
post_lists.append("No.{}".format(str(count)) + str(post) + "<br>")
return HttpResponse(post_lists)

创建homepage()获取所有数据,添加到post_lists再返回输出到用户端浏览器页面。

修改urls.py 网址与程序间的对应工作。

1
2
3
4
5
6
7
8
from django.conf.urls import url
from django.contrib import admin
from mainsite.views import homepage

urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', homepage),
]

我出现了编码错误,去错误的文件里面增加这个就可以了。

1
2
3
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

url(r'^$', homepage),这句话表示当用户浏览网址没有加任何字符串(根网址)的话,调用homepage().

  • 简单美化

修改views.py:

1
2
3
for count, post in enumerate(posts):
post_lists.append("No.{}".format(str(count)) + str(post) + "<br>")
post_lists.append("<small>" + str(post.body.encode('utf-8')) + "</small><br><br>")

这样做是不明智的,因为是MTV架构,应该放在template中,让template中的.html来负责正真的显示工作。

输出模板

通过template模板,当网站有数据输出时,通过渲染函数(render, 网页显示)把数据放在模板制定的位置。得到结果后交给HttpResponse()输出.

先mkdir 一个 templates

修改settings.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
TEMPLATES = [

{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]

修改views.py

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
reload(sys)
sys.setdefaultencoding("utf-8")

from datetime import datetime
from django.template.loader import get_template
from django.shortcuts import render
from django.http import HttpResponse
from .models import Post
# Create your views here

def homepage(request):
template = get_template('index.html')
posts = Post.objects.all()
now = datetime.now()
html = template.render(locals())
return HttpResponse(html)

这里使用locals(),把当前内存中的所有局部变量使用字典类型打包。

templates目录下,创建一个index.html模板文件。:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>
huchi's Django
</title>
</head>
<body>
<h1>huchi's Django</h1>
<hr>
{{posts}}
<hr>
<h3>time:{{now}}</h3>
</body>
</html>

可以测试一下。

再稍微改一下index.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>
huchi's Django
</title>
</head>
<body>
<h1>huchi's Django</h1>
<hr>
{% for post in posts %}
<p style='font-family:微软雅黑; font-size:16pt; font-weight:bold;'>
{{post.title}}
</p>
<p style='font-family:微软雅黑; font-size:10pt; letter-spacing:1pt;'>
{{post.body}}
</p>
{% endfor %}
<hr>
<h3>time:{{now}}</h3>
</body>
</html>

或者把中间一段改成带有链接的:

1
2
3
4
5
{% for post in posts %}
<p style='font-family:微软雅黑; font-size:16pt; font-weight:bold;'>
<a href='/post/{{post.slug}}'>{{ post.title }}</a>
</p>
{% endfor %}

接下来就要显示单张网页了。

修改urls.py:

1
2
3
4
5
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', homepage),
url(r'^post/(\w+)$', showpost),
]

然后滚到views.py写showpost(),顺便设置了一个重定向……

1
2
3
4
5
6
7
8
9
10
11
12
from django.shortcuts import redirect
...

def showpost(request, slug):
template = get_template('post.html')
try:
post = Post.objects.get(slug=slug)
if post != None:
html = template.render(locals())
return HttpResponse(html)
except:
return redirect('/')

在滚去写post.html…..:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>
huchi's Django
</title>
</head>
<body>
<h1>{{ post.title }}</h1>
<hr>
<p style='font-family:微软雅黑; font-size:10pt; letter-spacing:1pt;'>
{{ post.body }}
</p>
<hr>
<h3><a href='/'>回首页<a></h3>
</body>
</html>

不过发现其实和index.html重复的地方很多。

  • 共享模板
文件名Function
base.html基础模板
header.html放置共享的标题元素,比如网站Logo
footer.html共享网页,放置版权声明或其他声明
index.html首页
post.html单篇内容

开始搬砖。。。。。

base.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!--base.html-->
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>
{% block title %} {% endblock %}
</title>
</head>
<body>
{% include 'header.html' %}
{% block headmessage %} {% endblock %}
<hr>
{% block content %} {% endblock %}
<hr>
{% include 'footer.html' %}
</body>
</html>

include .html可以导入制定的文件。block 指令划分区块。

修改index.html:

1
2
3
4
5
6
7
8
9
10
11
12
13
<!-- index.html-->
{% extends 'base.html' %}
{% block title %}huchi's web{% endblock %}
{% block headmessage %}
<h3 style='font-family:楷体;'>本站列表</h3>
{% endblock %}
{% block content %}
{% for post in posts %}
<p style='font-family:微软雅黑;font-size:14pt;font-weight:blod;'>
<a href='/post/{{ post.slug }}'>{{ post.title }}</a>
</p>
{% endfor %}
{% endblock %}

修改post.html:

1
2
3
4
5
6
7
8
9
10
11
12
<!--post.html-->
{% extends 'base.html' %}
{% block title %} {{ post.title }} {% endblock %}
{% block headmessage %}
<h3 style="font-family:微软雅黑;">{{ post.title }}</h3>
<a style="font-family:微软雅黑;" href='/'>回首页</a>
{% endblock %}
{% block content %}
<p style="font-family:微软雅黑; font-size:12pt; letter-spacing:1pt;">
{{ post.body }}
</p>
{% endblock %}

修改header.html:

1
2
<!--header.html-->
<h1 style="font-family:微软雅黑;">welcome to huchi's web</h1>

footer.html:

1
2
3
4
5
6
7
8
<!--footer.html-->
{% block footer %}
{% if now %}
<p style="font-family:微软雅黑;">时间: {{ now }}</p>
{% else %}
<p style="font-family:微软雅黑;">?唧唧唧?</p>
{% endif %}
{% endblock %}

js/css的运用

1
2
3
4
5
6
7
8
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">

<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

将这段bootstrap的代码加入到base.html里面。

可以稍微改一下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<body>
<div class='container-fluid'>
{% include 'header.html' %}
<div class='panel panel-default'>
<div class='panel-heading'>
{% block headmessage %} {% endblock %}
</div>
<hr>
<div class='panel-body'>
{% block content %} {% endblock %}
</div>
<hr>
<div class='panel-footer'>
{% include 'footer.html' %}
</div>
</div>
</div>
</body>
  • 图片

像图片这些不需要处理的文件一般放置在statci file文件中(static files)。需要在settings.py先配置一下。

1
2
3
4
STATIC_URL = '/static/'
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static'),
]

大概是这样的:

1
2
3
4
5
6
7
8
9
10
(Venv) huchi@huchi-Lenovo-ideapad-510S-14ISK:~/myweb/static$ tree
.
├── css
├── images
│   ├── backgroud_aLi.jpg
│   ├── backgroud_angelBeats.jpg
│   └── logo.png
└── js

3 directories, 3 files
1
2
3
4
5
6
7
8
<!--header.html-->
{% load staticfiles %}
<div class='well'>
<h1 style="font-family:微软雅黑;">
<img src="{% static 'images/logo.png' %}"/>
welcome to huchi's web
</h1>
</div>

js,css静态文件的导入也是如此。

template的数据是可以用filter过滤器以此来实现文章概要,HTML解析,Markdown解析。


文章目录
  1. 1. Django 起航
    1. 1.1. First Go
    2. 1.2. File parse
    3. 1.3. 数据表
    4. 1.4. 读取数据库中的内容
    5. 1.5. 输出模板
    6. 1.6. js/css的运用
|