1.Django安裝與運行


Django基本配置

Python的WEB框架有Django、Tornado、Flask 等多種,Django相較與其他WEB框架其優勢為:大而全,框架本身集成了ORM、模型綁定、模板引擎、緩存、Session等諸多功能

1.安裝

# windows 直接用pip進行安裝
pip install django
 
# 生成的django文件加入到系統環境變量

2.創建並啟動

創建
django-admin startproject mysite

運行
python manage.py runserver 127.0.0.1:8001

瀏覽器訪問:
http://
127.0.0.1:8001/
 
        

3.mysite目錄結構

mysite    #目錄
 - mysite      # 對整個程序進行配置
  - init
  - settings  # 配置文件
  - urls       # URL對應關系
  - wsgi      # 遵循WSIG規范,uwsgi + nginx
 - manage.py     # 管理Django程序:

Django業務配置

1.創建app

python manage.py startapp cmdb     -->Terminal里面運行

2.app目錄結構

# 目錄結構
- cmdb
    - migrations  #數據庫操作記錄(只是修改表結構的記錄)
    - init      #表示python數據包(python3中有無均可)
    - admin      #Django為我們提供的后台管理
    - apps      #配置當前app
    - models     #創建數據庫表結構,寫指定的類,通過命令可以創建數據庫結構
    - tests      #單元測試
    - views      #寫業務邏輯代碼,最重要的就是這個文件了

3.templates模板

(1)在templates目錄下生成要給用戶顯示的登錄頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        label{
            width: 80px;
            text-align: right;
            display: inline-block;
        }
    </style>
</head>
<body>
    <form action="/login" method="post">
        <p>
            <label for="username">用戶名:</label>
            <input id="username" name="user" type="text" />
        </p>
        <p>
            <label for="password">密碼:</label>
            <input id="password" name="pwd" type="password" />
            <input type="submit" value="提交" />
        </p>
    </form>
</body>
</html>
login.html

(2)修改urls文件增加login路徑

from django.conf.urls import url
from django.contrib import admin
from cmdb import views        #導入views模塊

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login', views.login),       #添加login.html的url,后面要加逗號
]

(3)修改view文件,對數據進行處理

from django.shortcuts import HttpResponse
from django.shortcuts import render
 
def login(request):
    return render(request,'login.html')
 
    # 上面代碼等同於這個
    # f = open('templates/login.html','r',encoding='utf-8')
    # data = f.read()
    # f.close()
    # return HttpResponse(data)

(4)配置靜態文件static路徑

靜態文件static里面是存放css和js文件的,要想顯示相應的樣式,必須先修改settings文件配置

# settings.py文件里增加下面內容
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)

配置完路勁后就可以用css和js文件了

Django表單交互

1.獲取表單提交類型做相應處理,用戶名密碼輸正確跳轉到頁面,輸入錯誤有提示信息

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/commons.css" />
    <style>
        label{
            width: 80px;
            text-align: right;
            display: inline-block;
        }
    </style>
</head>
<body>
    <form action="/login/" method="post">
        <p>
            <label for="username">用戶名:</label>
            <input id="username" name="user" type="text" />
        </p>
        <p>
            <label for="password">密碼:</label>
            <input id="password" name="pwd" type="password" />
            <input type="submit" value="提交" />
            <span style="color: red;">{{ error_msg }}</span>
        </p>
    </form>

</body>
</html>
login.html
from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect


def login(request):
    # request  包含了用戶提交的所有信息
    # print(request.method)

    error_msg = ''
    if request.method == 'POST':
        user = request.POST.get('user', None)
        pwd = request.POST.get('pwd', None)
        if user == 'root' and pwd == '123':
            # 去跳轉
            return redirect('http://www.baidu.com')
        else:
            error_msg = '用戶名或密碼錯誤'

    return render(request, 'login.html', {'error_msg': error_msg})

2.模擬數據庫交互

訪問login界面,用戶輸入用戶名跳轉到home頁面

(1)登陸頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="/static/commons.css" />
    <style>
        label{
            width: 80px;
            text-align: right;
            display: inline-block;
        }
    </style>
</head>
<body>
    <form action="/login/" method="post">
        <p>
            <label for="username">用戶名:</label>
            <input id="username" name="user" type="text" />
        </p>
        <p>
            <label for="password">密碼:</label>
            <input id="password" name="pwd" type="password" />
            <input type="submit" value="提交" />
            <span style="color: red;">{{ error_msg }}</span>
        </p>
    </form>

</body>
</html>
login.html

(2)home頁面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body style="margin: 0">
    <div style="height: 48px;background-color: #dddddd"></div>
    <div>
        <form action="/home/" method="post">
            <input type="text" name="username" placeholder="用戶名" />
            <input type="text" name="email"  placeholder="郵箱"/>
            <input type="text" name="gender"  placeholder="性別"/>
            <input type="submit" value="添加" />
        </form>
    </div>
    <div>
        <table>
            {% for row in user_list %}
                <tr>
                    <td>{{ row.username }}</td>
                    <td>{{ row.gender }}</td>
                    <td>{{ row.email }}</td>
                </tr>
            {% endfor %}

        </table>
    </div>


</body>
</html>
home.html

(3)修改view文件,對輸入的內容進行處理

from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect

def login(request):
    # request  包含了用戶提交的所有信息
    # print(request.method)

    error_msg = ''
    if request.method == 'POST':
        user = request.POST.get('user', None)
        pwd = request.POST.get('pwd', None)
        if user == 'root' and pwd == '123':
            # 去跳轉
            return redirect('/home')
        else:
            error_msg = '用戶名或密碼錯誤'

    return render(request, 'login.html', {'error_msg': error_msg})

USER_LIST = [
    {'id': 1, 'username': 'derek', 'email': '111', "gender": ''},
    {'id': 2, 'username': 'jack', 'email': '222', "gender": '女'},
    {"id": 3, 'username': 'tom', 'email': '333', "gender": ''},
]

def home(request):
    if request.method == "POST":
        # 獲取用戶提交的數據 POST請求中
        u = request.POST.get('username')
        e = request.POST.get('email')
        g = request.POST.get('gender')
        temp = {'username': u, 'email': e, "gender": g}
        USER_LIST.append(temp)
    return render(request, 'home.html', {'user_list': USER_LIST})

3.獲取checkbox多個值

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login/" method="POST" >
        <p>
            111:<input type="checkbox"  name="favor" value="11"/>
            222:<input type="checkbox" name="favor" value="22"/>
            333:<input type="checkbox" name="favor" value="33"/>
        </p>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>
login

修改views.py文件對表單處理

from django.shortcuts import HttpResponse
from django.shortcuts import render
from django.shortcuts import redirect


def login(request):
    #checkbox  多選框
    if request.method == "POST":
        favor_list = request.POST.getlist("favor")      #getlist獲取多個值
        print(favor_list)           #多選框獲取到的是列表格式
        #['11', '22', '33']
        return render(request,"login.html")
    elif request.method == "GET":
        return render(request,"login.html")
    else:
        print("other")

當用戶提交之后,在后台上可以獲取用戶提交的信息,如下圖

4.上傳文件file

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/login" method="POST" enctype="multipart/form-data">
        <p>
            <input type="file" name="files"/>
        </p>
        <input type="submit" value="提交"/>
    </form>
</body>
</html>
login.html

views.py

from django.shortcuts import render,HttpResponse
import os
def login(request):
    #file 上傳文件
    if request.method == "POST":
        obj = request.FILES.get('files')       #用files獲取文件對象
        if obj:
            print(obj, type(obj), obj.name)
            # test.jpg <class 'django.core.files.uploadedfile.InMemoryUploadedFile'> test.jpg
            import os
            file_path = os.path.join('upload', obj.name) #保存用戶上傳文件的路勁
            f = open(file_path, "wb")
            for item in obj.chunks():      #chunks表示所有的數據塊,是個迭代器
                f.write(item)
            f.close()
        return render(request,"login.html")
    elif request.method == "GET":
        return render(request,"login.html")
    else:
        print("other")

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM