環(huán)境安裝和配置
pip install virtualenv -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install virtualenvwrapper-win
mkvirtualenv web #創(chuàng)建虛擬環(huán)境
workon web #切換到虛擬機(jī)環(huán)境
pip install django==2.2.7
#settings.py
ALLOWED_HOSTS = ['*']
LANGUAGE_CODE = 'zh-hans'
#TIME_ZONE = 'UTC'
USE_TZ = False
應(yīng)用環(huán)境配置
創(chuàng)建應(yīng)用
>cd <項(xiàng)目目錄>
>python manage.py startapp blog
-
migrations
遷移文件集合
admin.py:項(xiàng)目的后臺(tái)
apps.py:應(yīng)用設(shè)置
models.py:模型(數(shù)據(jù)庫(kù))
views.py:視圖(頁(yè)面請(qǐng)求和響應(yīng))
注冊(cè)應(yīng)用
- 修改settings.py
INSTALLED_APPS = [
...
'blog.apps.BlogConfig'
]
數(shù)據(jù)庫(kù)配置
啟動(dòng)mysql服務(wù)
-
[shuyun@master ~]$ sudo service mysqld start Starting mysqld: [ OK ]
- 數(shù)據(jù)庫(kù)連接參數(shù):
- 用戶: root
- 密碼:123456
- 端口:3306
- 數(shù)據(jù)庫(kù)連接參數(shù):
確認(rèn)虛擬機(jī)IP
[shuyun@master ~]$ ifconfig
eth5 Link encap:Ethernet HWaddr 00:50:56:3A:1F:12
inet addr:192.168.89.200 Bcast:192.168.89.255 Mask:255.255.255.0
-
settings.py完成mysql配置
-
開發(fā)環(huán)境
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } }
生產(chǎn)環(huán)境
-
DATABASES = {
'default':{
'ENGINE':'django.db.backends.mysql',
'NAME':'blog',
'USER':'root',
'PASSWORD':'123456',
'HOST':'192.168.89.200',
'PORT':3306,
}
}
安裝pymysql
pip install PyMySQL
修改blogproj/init.py
import pymysql
pymysql.install_as_MySQLdb()
創(chuàng)建數(shù)據(jù)庫(kù)和授權(quán)
[root@master ~]# mysql -uroot -p123456
mysql> create database blog;
mysql> grant all on blog.* to root@'%' identified by '123456';
創(chuàng)建管理員賬號(hào)
用戶:admin党涕,密碼:admin
python manage.py createsuperuser
數(shù)據(jù)模型
在models.py中完成如下配置
博客模型
from django.db import models
from django.contrib.auth.models import User
#文章類別
class Category(models.Model):
#默認(rèn)自動(dòng)生成id字段作為主鍵
name = models.CharField(verbose_name='名稱', max_length=100)
#標(biāo)簽
class Tag(models.Model):
#默認(rèn)自動(dòng)生成id字段作為主鍵
name = models.CharField(verbose_name='名稱', max_length=100)
class Post(models.Model):
title = models.CharField(verbose_name='標(biāo)題', max_length=100)
body = models.TextField(verbose_name='正文') #TextField存儲(chǔ)大段文本
create_time = models.DateTimeField(verbose_name='創(chuàng)建時(shí)間')
modified_time = models.DateTimeField(verbose_name='修改時(shí)間')
excerpt = models.CharField(verbose_name='摘要',max_length=255)
category = models.ForeignKey(Category, on_delete=models.CASCADE,verbose_name='類別') #一對(duì)多
tags = models.ManyToManyField(Tag, blank=True,verbose_name='標(biāo)簽') #多對(duì)多
author = models.ForeignKey(User,on_delete=models.CASCADE,verbose_name='用戶')
數(shù)據(jù)庫(kù)遷移
python manage.py makemigrations #創(chuàng)建遷移文件
python manage.py migrate #遷移到數(shù)據(jù)庫(kù)
ORM操作
存數(shù)據(jù)
>python manage.py shell
In [1]: from blog.models import Category,Tag,Post
#寫入類別
In [2]: cate = Category(name='test cate1')
In [3]: cate.save()
#寫入標(biāo)簽
In [4]: tag = Tag(name='test tag1')
In [5]: tag.save()
#寫入博客
In [2]: from django.contrib.auth.models import User
In [8]: from django.utils import timezone
In [4]: user = User.objects.get(username='admin')
In [7]: post = Post(title='title_test1',body='body_test1',create_time=timezone.now(),modified_time=timezone.now(),category=cate,author=user)
post.save()
讀數(shù)據(jù)
#讀取category
In [18]: cateall = Category.objects.all()
In [19]: cateall
Out[19]: <QuerySet [<Category: Category object (1)>, <Category: Category object (2)>]>
In [20]: cateall[0]
Out[20]: <Category: Category object (1)>
In [21]: cateall[0].name
Out[21]: 'test cate1'
#TODO練習(xí):讀取post的body數(shù)據(jù)
In [22]: post = Post.objects.all()
In [23]: post[0].body
Out[23]: 'body_test1'
刪數(shù)據(jù)
#刪類別
In [24]: cate1 = Category.objects.get(name='test cate1')
In [26]: cate1.delete()
Out[26]: (1, {'blog.Category': 1})
#TODO練習(xí):刪除post數(shù)據(jù)
In [27]: post = Post.objects.get(id=1)
In [28]: post.delete()
Out[28]: (1, {'blog.Post_tags': 0, 'blog.Post': 1})
視圖
視圖函數(shù)
-
修改了blog/views.py
from django.http import HttpResponse def index(request): return HttpResponse("歡迎學(xué)習(xí)Django讲婚!")
URL綁定
-
配置項(xiàng)目URL:blogproj/urls.py
.... from django.conf.urls import url,include urlpatterns = [ ... url(r'',include('blog.urls')) ]
-
在blog項(xiàng)目目錄下創(chuàng)建urls.py文件
-
添加代碼
from django.conf.urls import url,include from . import views urlpatterns = [ url(r'', views.index, name='index') ]
-
-
啟動(dòng)開發(fā)服務(wù)
python manage.py runserver #默認(rèn)8000端口 #Starting development server at http://127.0.0.1:8000/ python manage.py runserver 127.0.0.1:8001 #指定端口啟動(dòng)
瀏覽器訪問
模板系統(tǒng)
模板指靜態(tài)頁(yè)面(html)
靜態(tài)文件:css肴熏、js
-
創(chuàng)建templates/blog目錄卧晓,新建index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>{{ title }}</title> </head> <body> <h1>{{ welcome }}</h1> </body> </html>
{{ title }}怠晴,{{ welcome }}:模板變量
- 修改views.py
def index(request):
context = {'title':"Dylan的Blog", 'welcome':'歡迎來到我的博客'}
return render(request, 'blog/index.html', context=context)
-
刷新頁(yè)面
博客首頁(yè)
靜態(tài)文件
- 拷貝模板
- 項(xiàng)目目錄下創(chuàng)建static/blog目錄
- 拷貝css和js到上述目錄
- 拷貝index.html到templates/blog目錄
- 修改settings
STATIC_ROOT = os.path.join(BASE_DIR,'static') #新增
- 修改index.html
{% load static %}
...
<!-- css -->
<link rel="stylesheet" href="{% static 'blog/css/bootstrap.min.css' %}">
<link rel="stylesheet" >
<link rel="stylesheet" href="{% static 'blog/css/pace.css' %}">
<link rel="stylesheet" href="{% static 'blog/css/custom.css' %}">
<!-- js -->
<script src="{% static 'blog/js/jquery-2.1.3.min.js' %}"></script>
<script src="{% static 'blog/js/bootstrap.min.js' %}"></script>
<script src="{% static 'blog/js/pace.min.js' %}"></script>
<script src="{% static 'blog/js/modernizr.custom.js' %}"></script>
</head>
...
<script src="{% static 'blog/js/script.js' %}"></script>
</body>
...