1. 程式人生 > 其它 >Django基礎一安裝、建立專案和目錄結構

Django基礎一安裝、建立專案和目錄結構

Django基礎一安裝、建立專案和目錄結構

目錄

1. Django介紹

Django是一個開放原始碼的Web應用框架,由Python寫成。採用了MTV(model–template–views)的軟體設計模式,即模型(Model),檢視(View)和模板(Template)。它在開發初期用於管理勞倫斯出版集團旗下的一些以新聞為主的網站。Django於2005年7月在BSD許可證下發布,它的名字來源於比利時的吉普賽爵士吉他手金格·萊恩哈特。

官方網站:https://www.djangoproject.com/

1.1 安裝Django

前提是已經預設安裝完了Python,目前官方網站上DjangoPython對應的版本:

Django 版本 Python 版本
1.8 2.7,3.2,3.3,3.4,3.5
1.9,1.10 2.7,3.4,3.5
1.11 2.7,3.4,3.5.3.6,3.7(1.11.17新增)
2.0 3.4,3.5.3.6,3.7
2.1 3.5.3.6,3.7
2.2 3.5,3.6,3.7,3.8(2.2.8 新增),3.9(2.2.17 新增)
3.0 3.6,3.7,3.8,3.9 (3.0.11 新增)
3.1 3.6,3.7,3.8,3.9(3.1.3 新增)
3.2 3.6, 3.7, 3.8, 3.9, 3.10 (在 3.2.9 中就已經加入了)
4.0 3.8,3.9,3.10
1. Python版本:
python --version
Python 3.10.0
2. pip版本
pip --version
pip 22.0.3 from D:\Program Files\python\lib\site-packages\pip (python 3.10)
3.安裝Djang
pip install Django==3.2(指定版本)

4.驗證Django是否安裝成功
python
>>> import django
>>> print(django.get_version())
3.2

1.2 利用Django建立專案

1.2.1 利用命令列建立

>django-admin startproject firstDjango  # 建立專案
>cd firstDjango		# 進入到專案目錄
>python manage.py runserver		# 啟動專案
'''
	python manage.py runserver 預設啟動地址為:http://127.0.0.1:8000/
	如果想更換IP和埠:
		python manage.py runserver [ip:port]
		ip為自己設定的ip地址
		port為自己想設定的埠
'''
建立APP:
   	python manage.py startapp  app的名字

訪問啟動的Django:

1.2.2 利用Pycharm建立

就建立好了,然後啟動:

1.2.3 什麼是APP

Django是專門開發APP的軟體 。

那麼Django中的APP是什麼?

例子:
    利用Django建立了一個專案就相當於建立了一個大學,裡面的APP就相當於是大學裡面的學院。每個學院都可以有自己獨立的功能和職責。
    
    還比如使用Django建立了一個電商網站,裡面的APP就相當於是各項功能:	
    訂單功能
    購物車功能
    等等


1.3 命令列建立和Pycharm建立Django的區別

會發現Pycharm裡面比命令列多了一個templates目錄和fisrt目錄,這兩個目錄是Pycharm 自動建立的。first目錄就是app. 如果使用Pycharm建立專案的時候在Application name沒有輸入則不會自動建立APP,如果沒有建立則可使用命令列自己建立:

python manage.py startapp first

這是目錄上的差別,還有一處差別是settings.py檔案中:

命令列安裝settings.py:
    DEBUG = True   # 生產上把DEBUG改成false

	ALLOWED_HOSTS = []  # 在Linux環境部署時[*],代表誰都能訪問
    
    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

    TEMPLATES = [
    {
        'DIRS': [],
        
Pycharm安裝:
settings.py:
    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first.apps.FirstConfig',
]
    TEMPLATES = [
    {
        'DIRS': [BASE_DIR / 'templates']
        
#  Pycharm裡面:
        INSTALLED_APPS: 多了一行'first.apps.FirstConfig',
        TEMPLATES:DIRS裡面有資料,'DIRS': [BASE_DIR / 'templates'] 
       

INSTALL_APPS是註冊,'''我們建立的app一定要去settings檔案中INSTALL_APPS裡註冊才能生效'''
        
    INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'first.apps.FirstConfig', # 這是完整寫法
    'first' # 這是簡稱
]      
這兩種寫法都可以
        
        
TEMPLATES  'DIRS': [BASE_DIR / 'templates']   '''指定template的目錄,這個目錄主要是放網頁檔案的。不加的找不到這個目錄'''

        1.x 版本:
        'DIRS': [os.path.join(BASE_DIR,'templates')] 
       
"""
總結:
命令列不會自動建立templates模板資料夾
命令列不會自動在配置檔案中配置模板資料夾路徑
命令列也不會自動建立APP
"""
        

1.4 Django目錄結構

\firstDjango 		# 專案名
├─first    			# 應用名目錄
│  ├─migrations		# 用來儲存資料庫相關(類似操作日誌)
│  │  └─__init.py__
│  └─__admin.py		# Django的後臺管理
│  └─__apps.py		# 註冊APP
│  └─__models.py	# 資料庫相關(模型層)
│  └─__tests.py		# 測試檔案
│  └─__views.py		#  檢視函式(檢視層)
│  └─__init__.py
├─firstDjango   	# 和專案同名目錄
│  └─__asgi.py  	# 為了支援非同步網路伺服器和應用而新出現的 Python 標準。
│  └─__settings.py	# Django給使用者配置的配置檔案
│  └─__urls.py		# 路由與檢視函式(可是函式,也可以是類)對應關係(路由層)
│  └─__wsgi.py		# wsgiref模組,Django主要的部署方式
│  └─__init__.py
├─manage.py   		# Django入口檔案
├─db.sqlite3		# Django自帶的資料庫
└─templates			# 模板目錄儲存HTML目錄(模板層)

1.5 Django必會

**HttpResponse **

HttpResponse # 返回字串
    """要返回字串使用:HttpResponse"""
    # 要增加一個訪問地址:http://127.0.0.1:8000/index
    1, 要在路由與檢視函式對應關係的urls.py裡匯入first這個APP
    """
    from django.contrib import admin
    from django.urls import path
    from first import views

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('index/', views.index),
    ]
    """

    2, 要在views.py裡增具體的的處理函式
    """
    from django.shortcuts import render,HttpResponse

    # Create your views here.

    def index(request):
        return  HttpResponse("Hello Django")

    """

render

render # 返回html頁面
urls.py:
"""
    from django.contrib import admin
    from django.urls import path
    from first import views

    urlpatterns = [
        path('admin/', admin.site.urls),
        path('html/', views.web),

    ]
"""
views.py:
    """
    from django.shortcuts import render
	def web(request):
        return render(request, 'test.html')
    """
    
templates目錄:
    text.html
"""    
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>返回的第一個HTML頁面</h1>
</body>
</html>
"""

也可以從後端拿值在頁面上顯示:
    views.py
    """
    from django.shortcuts import render,HttpResponse
    
    def html(request):
        flist = [1,2,3,4,5]
        return render(request, 'test.html',{'flist':flist})
    """
    text.html
    """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
        <h1>返回的第一個HTML頁面</h1>
        <table >
        <thead>
        <tr>
            <th>id</th>
        </tr>
        </thead>
        <tbody>
            {% for foo in flist %}
            <tr>
                <td>{{ foo }}</td>
            </tr>
            {% endfor %}
        </tbody>
    </table>
    </body>
    </html>
    """
 
locals()  #檢視全部區域性變數
globals() #檢視全部全域性蠻

redirct

redirct:重定向
    
urls.py 
"""
from django.contrib import admin
from django.urls import path
from first import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('index/', views.index),
    path('html/', views.html),
    path('web/', views.web),

]

"""
views.py
"""
from django.shortcuts import render,redirect
def web(request):
    return redirect('http://www.pymysql.com')
    
"""
訪問http://127.0.0.1:8000/web就會跳到http://www.pymysql.com

2 練習把資料庫中的某個表的資料在通過Django展示出來

資料庫:
    1. 建立資料庫:
        create database firstDjango
    2. 建立表:
        create table test1(id int, name varchar(255), age int);
    3. 插入資料:
    insert into test1 values(1,'Hans', 18),(2,'Hello', 20),(3,'Hi', 30);
    (省略建立遠端連線使用者和授權步驟)
    
Django:
    
firstDjango目錄    
urls.py
	"""
	from django.contrib import admin
    from django.urls import path
    from first import views
    
    urlpatterns = [
    path('admin/', admin.site.urls),
    path('db/', views.db),
	]
	"""
first目錄
views.py
"""
def mysqlData():
    from django.shortcuts import render,HttpResponse,redirect
    import pymysql
    
	def mysqlData():   # 獲取資料庫資料
    conn = pymysql.connect(
        host='192.168.1.109',
        user='root',
        password='123456',
        port=3306,
        database='firstDjango',
        charset='utf8'
    )
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    sql='select * from test1'
    cursor.execute(sql)
    data = cursor.fetchall()
    return data

def db(request):
    data = mysqlData()
    return render(request, 'db.html',{"data":data})

"""

templates目錄下:
    db.html
    """
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
        <link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
        <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/3.4.1/js/bootstrap.min.js"></script>
    </head>
    <body>
    <div class="container">
       <table class="table table-striped table-hover">
            <thead>
            <tr>
                <th>id</th>
                <th>name</th>
                <th>age</th>
            </tr>
            </thead>
            <tbody>
                {% for foo in data %}
                <tr>
                    <td class="success">{{ foo.id }}</td>
                    <td class="warning">{{ foo.name }}</td>
                    <td class="danger">{{ foo.age }}</td>
                </tr>
                {% endfor %}
            </tbody>
        </table>
    </div>
    </body>
    </html>
    
    """
訪問: