● Server建立

 

1. 安裝 Django

$ pip install django

 

2. 選擇自己要建立網站的資料夾位置

如: $ CD C:\myPython\

 

3.建立空資料夾存放專案(用來存放使用django建立的站點) 此步驟可省略

$ mkdir django_test

 

4. 使用django-admin建立專案站點

$ django-admin startproject mytestsite

image

 

5. 將目錄切換至新增站點的位置(manage.py的資料夾位置)

image

 

6. 執行啟動網站指令

$ python manage.py runserver

 

7. 開啟網站127.0.0.1:8000

執行成功畫面如下

image

 

以上操作過程如下

image

 

Reference-----------------------------------------------------------------------------------------------

https://github.com/twtrubiks/django-tutorial

https://developer.mozilla.org/zh-TW/docs/Learn/Server-side/Django

---------------------------------------------------------------------------------------------------------

 

● APP建立

 

1.建立templates資料夾

$mkdir templates

 

2. 設定 Templates 資料夾的位置

編輯setting.py

新增import os

修改TEMPLATES下的DIRS

將'DIRS':[ ]的內容修改為 [os.path.join(BASE_DIR, 'templates').replace('\\', '/')]

image

image

image

 

3.建立APP命名為musics

$python manage.py startapp musics

執行後會新增一個musics的資料夾

image

 

2. 將新增的APP加入站點設定檔

修改[mytestsite]資料夾下的setting.py

將APP名稱musics加入INSTALLED_APPS內

image

 

3. 新增html檔案進行測試

在[templates]資料夾下新增檔案命名為hello_world.html

image

編輯內容如下

<!DOCTYPE html>
<html>
    <head>
        <title>I come from template!!</title>
    </head>
    <body>
        <h1>Hello World!</h1>
        <h1>{{data}}</h1>
    </body>
</html>

{{data}}為APP views.py傳回的內容

 

3. 設定APP的views

修改APP資料夾[musics]內的views.py

新增回傳值的function, 回傳內容為Hello Django.

def hello_view(request):
    return render(request, 'hello_world.html', {
        'data': "Hello Django ",
    })

image

 

4. 設定站點的URLconf

編輯站點[mytestsite]資料夾的urls.py

url(regex, view)

regex為正規化, 'hello/' 代表的是 hello/ 這種 URL

view為對應的function名稱

from django.conf.urls import url
from musics.views import hello_view

urlpatterns = [
    url('hello/', hello_view)
]

image

 

5. 啟動Server

$python manage.py runserver

image

離開請按 [Ctrl]+[C]

image

 

MTV

MVC

Model

Model

Template

View

View

Controller

MVC相對應架構

 

image

執行順序與關聯

 

mysite/
├── manage.py 
├── [mysite] 
        ├── __init__.py 
        ├── settings.py 
        ├── urls.py 
        └── wsgi.py
├── [APP Musics]
        ├── __init__.py
        ├── admin.py
        ├── apps.py
        ├── models.py
        ├── tests.py
        └── views
├── [templates]
        └── hello_world.html

專案結構

Reference-----------------------------------------------------------------------------------------------

https://djangogirlstaipei.gitbooks.io/django-girls-taipei-tutorial/content/django/templates.html

----------------------------------------------------------------------------------------------------------

 

● Home page設定

當直接瀏覽Server網址時出現錯誤404, 這是因未將主頁home指向頁面.

image

 

編輯urls.py, 新增url指向hollo_view, 這樣下次瀏覽時就會

url(r'^$', hello_view)

 

透過Models定義資料表與更新資料庫

1. 資料庫設定存放於 mytestsite/settings.py

預設為DB為SQLite 3

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

 

2. 透過Models定義資料表與資料型態

musics/models.py

from django.db import models

# Create your models here.
class Music(models.Model):
    song = models.TextField(default="song")
    singer = models.TextField(default="AKB48")
    last_modify_date = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

default : 代表默認值,也就是如果你沒有指定的話會用默認值。
auto_now_add : 新增時會幚你自動加上建立時間。
auto_now : 資料有更新時會幚你自動加上更新的時間。

 

3. 建立資料表完成遷移(migration)

$python manage.py makemigrations

makemigrations : 為Models內容有變動時,建立一個檔案記錄更新內容 .

下圖中新生成的記錄檔為 migrations\0001_initial.py

image

 

$python manage.py migrate

migrate: 根據migrations生成的記錄檔更新DB

image

 

執行後, 除新增原本預設資料表, 也新增一個在models定義的資料表名稱music.

image

 

若要指定APP Musics更新,則執行$python manage.py makemigrations musics.

image

Reference-----------------------------------------------------------------------------------------------

https://djangogirlstaipei.gitbooks.io/django-girls-taipei-tutorial/content/django/models.html

----------------------------------------------------------------------------------------------------------

 

將新DB的內容轉為Models

執行指令後, 在manage.py的同層資料夾, 新增了model.py, 內容存放在資料庫轉換後的資料描述.

$python manage.py inspectdb > models.py

image

 

●透過Django管理資料庫

Django有內建資料庫後台管理頁面

1. 建立資料庫管理者

$python manage.py createsuperuser

執行指令依據設定管理者資料

image

 

2. 修改mytestsite\urls.py

新增參數將admin指向資料庫管理頁面

from django.contrib import admin

url('admin', admin.site.urls)

from musics.views import hello_view
from django.conf.urls import url
from django.contrib import admin

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

 

3. 執行runserver, 進入http://127.0.0.1:8000/admin.

If no table show, you must excute next setp.

image

image

3.透過migrations/amin.py 修飾版面顯示

from django.contrib import admin
from musics.models import Music

class MusicAdmin(admin.ModelAdmin):
    list_display = ('id','song','singer','year')
admin.site.register(Music, MusicAdmin)

image

Reference-----------------------------------------------------------------------------------------------

https://github.com/twtrubiks/django-tutorial

https://www.learncodewithmike.com/2020/03/django-administration.html

----------------------------------------------------------------------------------------------------------

 

● Post資料給Server並回傳

1.APP資料夾 musics/views.py新增function

def post(request):
    if request.method == "POST":
        mess = request.POST['username']
    else:
        mess = "表單資料尚未送出!"
    return render(request,"post.html",locals())

 

2.Templates資料夾新增post.heml

<body>
<form action="/post" method="POST" name="form1">
        {% csrf_token %}  <!-- 啟動CSRF防護,保護伺服器避免被攻擊 -->
        <div>請輸入姓名:<input type="text" name="username">
            <input type="submit" value="送出資料">
        </div>
        <div>接收到的資料:{{mess}}</div>
</form>
</body>

 

3.Site資料夾 mytestsite/urls.py 新增url定義

from musics.views import post
from django.conf.urls import url

urlpatterns = [
    url('post', post)
]

 

執行結果如下

image

image

Reference-----------------------------------------------------------------------------------------------

https://ivanjo39191.pixnet.net/blog/post/145765899

----------------------------------------------------------------------------------------------------------

●圖片讀取

1. 設定靜態資料讀取路徑

編輯mytestsite/setting.py

指定靜態資料路徑

STATIC_URL = '/static/'

STATICFILES_DIRS = [os.path.join(BASE_DIR, "static") ]

 

2. 新增回傳圖片路徑

編輯musics/views.py

新增image='/static/images/test.jpg'

def post(request):
    if request.method == "POST":        #如果是以POST的方式才處理
        name = request.POST['username'] #取得表單輸入資料
        image='/static/images/test.jpg'
    else:
        mess = "表單資料尚未送出!"
    return render(request,"post.html",locals())

 

3. 編輯templates/post.html

{% load static %}

<img src="{{image}}"></img>

 

4. 新增圖片儲存資料夾

在app資料夾musics下新增資料夾[static]

在資料夾[static]下新增資料夾[images]

將圖片放置於[images]資料夾內

image

 

● runserver指定IP

$python manage.py runserver 192.168.0.101:8010

執行指定命令後, 開啟網頁出現錯誤訊息.

You may need to add '192.168.0.101' to ALLOWED_HOSTS.

image

編輯mytestsite\setting.py

在ALLOWED_HOSTS添加指定IP或萬用字元 ' * '

ALLOWED_HOSTS = ['*']

image

 

● 透過類似ajax模式局部更新回傳的Json object

image

html

<!DOCTYPE html>
<html>
    <head>
        <title>-Home-</title>

    {% load static %}
    <script src="{% static 'scripts/jquery-3.4.1.min.js' %}"></script>
        <style>
            .home-style{
                color:#5566ff;
            }
        </style>
    </head>
    <body>
<p>result: <span class="home-style" id='result'></span></p>
    <div id="home">home</div>
    <div id="click">Click!</div>
        {% block content %}
        {% endblock %}

    <script>
        $('#home').attr('class','home-style');
        $(document).ready(function () {
           $("#click").click(function () {

                $.get("/ajax_test/",{'a':'a'}, function(ret){
                console.log(ret);
                    $('#result').html(ret.twz);
                });
           });
         });
    </script>
    </body>
</html>

 

views

from django.http import JsonResponse
def ajax_test(request):
    ajax_test = {'twz': 'Love python and Django', 'zqxt': 'I am teaching Django'}
    return JsonResponse(ajax_test)

 

urls

from musics.views import ajax_test

urlpatterns = [
    url(r'^$', home),
    url('hello/', hello_view),
    url('admin', admin.site.urls),
    url('post', post),
    url(r'^ajax_test/$', ajax_test)
]

 

單獨導向function

image

Reference-----------------------------------

https://code.ziqiangxuetang.com/django/django-ajax.html

-----------------------------------

 

● urls.py的設定參考

https://openhome.cc/Gossip/CodeData/PythonTutorial/ViewPy3.html

arrow
arrow
    全站熱搜

    門外漢 發表在 痞客邦 留言(0) 人氣()