日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Django安装使用基础

發布時間:2025/6/17 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Django安装使用基础 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

安裝Django

pip3 install django

windows安裝后,添加Django安裝路徑的環境變量。

1、創建Django工程

django-admin startproject 【工程名稱】 # 生成目錄結構如下mysite- mysite # 對整個程序進行配置- __init__.py - settings.py # 配置文件 - urls.py # URL對應關系 - wsgi.py # 遵循WSGI規范,一般使用 uwsgi + nginx - manage.py # 管理Django程序:如下 - python manage.py # 運行程序 - python manage.py startapp xx # 創建app # Django的orm框架 - python manage.py makemigrations - python manage.py migrate

SGI本質上就是一個封裝了socket的模塊,調用接口就可以。

  • 運行Django功能
python manage.py # 或如下 python manage.py runserver 0.0.0.0:8000

通過pycharm 也能創建django程序。

寫一個基本完整的http請求

編輯urls.py 文件

from django.conf.urls import url from django.contrib import admin from django.shortcuts import HttpResponse # Http相應 def home(request): return HttpResponse('<h1>Hello</h1>') urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^h.html/', home), ]

?

啟動后,訪問:127.0.0.1:8000/h.html/

不過實際中,上面的home相當于一個業務功能,而不同的功能,在django中可以分別創建不同的app。

2、創建Django app

  • 創建app
python manage.py startapp cmdb

把home函數移到cmdb\views.py中,

from django.shortcuts import HttpResponsedef home(request): return HttpResponse('<h1>Hello</h1>')

urls.py修改如下:

from django.conf.urls import url from django.contrib import admin from cmdb import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^h.html/', views.home), ]
  • app目錄結構
migrations # django orm框架,修改表結構的操作記錄(差異化) __init__ # python3中有沒有都一樣,python2中必須有 admin # Django為我們提供的后臺管理 apps # 配置當前app models # ORM:寫指定的類,通過命令可以創建數據庫結構 tests # 單元測試 views # ****業務代碼****

3、寫一個簡單的登錄注冊相應頁面

新建一個templates 文件夾,用來存放html模板文件

views.py

# from django.shortcuts import HttpResponse from django.shortcuts import render # django幫我們打開文件并相應的模塊 # 因為經常返回數據,打開文件,所以django使用render模塊,做這個事情。 def login(request): # with open("templates/login.html", "r", encoding="utf-8") as f: # data = f.read() # return HttpResponse(data) return render(request, 'login.html') # 這里沒有指定路徑,在settings配置里,默認就已添加templates

templates/login.html

<!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" type="text" /> </p> <p> <label for="password">密碼:</label> <input id="password" type="text" /> <input type="submit" value="提交" /> </p> </form> </body> </html>

?

  • js、css靜態文件處理

頁面里可能會包含css、js文件,這些靜態文件也需要引入進來。

創建靜態文件目錄static,創建完之后還要在settings里面配置一下,最后面添加:

STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), # 必須加上都好“,” 不加就報錯 )

login.html 文件中引入css、js

<link rel="stylesheet" href="/static/commons.css">

總結:

創建完project后,優先做幾件事:

1、配置模板的路徑

settings.py

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', ], }, }, ]

?

2、配置靜態目錄

# 創建static目錄# settings 最后添加靜態文件配置 STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'), ) # html模板文件引用css、js <link rel="stylesheet" href="/static/commons.css" />

4、獲取用戶請求信息并處理

  • 注釋掉CSRF

CSRF: 跨站請求偽造

后面會講,這里先注釋上,不然會報錯

settings —> 找到MIDDLEWARE —> 注釋掉

# 'django.middleware.csrf.CsrfViewMiddleware',

  • request 包含了客戶端發來的所有信息。

客戶端發過來的信息,內部django、wsgi幫我們處理,處理之后會給我們一個結果。把客戶端所有的信息打包然后發給我,怎么發呢?

就是上面函數形參 request :包含了客戶端用戶發來的所有信息。

比如:request.method就是用戶提交方式(get、post)。往往get獲取表單;post方式提交數據。

form表單提交的時候,以類似字典的形式提交,所以要在html form里定義name

from django.shortcuts import render # django幫我們打開文件并返回給用戶 from django.shortcuts import redirect # 重定向、跳轉 def login(request): # request 包含用戶提交的所有信息 error_msg = '' if request.method == "POST": # request.method 用戶提交方法 # request.POST 用戶通過POST提交過來的數據 user = request.POST.get('user', None) pwd = request.POST.get('pwd', None) # 不存在為None if user == 'root' and pwd == '123': # 用戶跳轉 return redirect("http://blog.csdn.net/fgf00") else: # 用戶名密碼錯誤。 error_msg = "用戶名或密碼錯誤" return render(request, 'login.html', {"error_msg":error_msg}) # "error_msg:網頁中定義的特殊文本,key"
  • Django模版語言

用戶名密碼錯誤,怎么給用戶返回數據?

需要借助另外一件事:在模板里面,在Django里面可以寫一些特殊的內容。

{{ }}?Django 對其進行替換。

<!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"> {# action="/home":提交到http://127.0.0.1/home/ #} <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="提交1" /> <span style="color: red">{{ error_msg }}</span> {# Django里面可以寫一些特殊的內容,后臺進行替換 #} </p> </form> </body> </html>

?

注意:網頁action提交那里action="/login/",要和urls.py 里url(r'^login/', views.login),保持一致!!!

要是login/全是login/,要是login全是login,否則點擊提交會報錯:

RuntimeError at /login You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/login/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings.

web框架中,之后Django中會報這個錯。

PS:配置過程中,可能會種種原因遇到報錯,這時候可以從django相應的過程中,逐步排查,最終找到錯誤點

5、前后端交互

urls.py :url(r'^home', views.home),

views.py

from django.shortcuts import render USER_LIST = [{'user':'alex', 'email': 'a.126.com', 'gender': "男"}, {'user':'lily', 'email': 'a.126.com', 'gender': "女"}, {'user':'fgf', 'email': 'a.126.com', 'gender': "男"}, ] def home(request): if request.method == "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})

?

templates/home.html

  • 注意下:django 模板語言for循環寫法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body style="margin: 0"> <div style="height: 48px;</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> {# django 模板語言for循環 (user_list:后端定義的全局變量) #} {% for row in user_list %} <tr> {# 這里row代表字典,去索引用row.email,而不是row['email'] #} <td>{{ row.username }}</td> <td>{{ row.gender }}</td> <td>{{ row.email }}</td> </tr> {% endfor %} </table> </div> </body> </html>

6、Django 請求 生命周期

  • 1)客戶端請求
  • 2)路由系統:urls.py,路由關系映射
  • 3)視圖函數:app/views.py,功能函數
  • 4)視圖函數從DB等取數據,并嵌套到html中(html模板templates中)。渲染或組合,最終生成字符串返回給用戶

?


?

7、django內容整理

  • 配置
1. 創建Django工程django-admin startproject 工程名2. 創建APPcd 工程名python manage.py startapp cmdb3、靜態文件project.settings.pySTATICFILES_DIRS = (os.path.join(BASE_DIR, "static"), ) 4、模板路徑 DIRS ==> [os.path.join(BASE_DIR,'templates'),] 5、settings中 middlerware # 注釋 csrf

?

  • 使用
6、定義路由規則urls.py"login" --> 函數名7、定義視圖函數app下views.pydef func(request): # request.method GET / POST # 獲取數據 # http://127.0.0.1:8009/home?nid=123&name=alex # request.GET.get('',None) # 獲取請求發來的數據 # request.POST.get('',None) # 返回數據 # return HttpResponse("字符串") # return render(request, "HTML模板的路徑") # return redirect('/只能填URL') # 只返回url地址,讓客戶端再次請求,不會把跳轉的數據發給客戶端 # redirect('/login') 前面的"/"代指本地url,前面的域名端口

?

  • 模板渲染
8、模板渲染特殊的模板語言-- {{ 變量名 }}views.pydef func(request): return render(request, "index.html", {'current_user': "fgf"}) index.html <html> .. <body> <div>{{current_user}}</div> </body> </html> ====> 最后生成的字符串,返回給用戶 <html> .. <body> <div>fgf</div> </body> </html> -- For循環 views.py def func(request): return render(request, "index.html", {'current_user': "alex", 'user_list': ['alex','eric']}) index.html <html> .. <body> <div>{{current_user}}</div> <ul> {% for row in user_list %} {% if row == "alex" %} <li>{{ row }}</li> {% endif %} {% endfor %} </ul> </body> </html> ###索引################# def func(request): return render(request, "index.html", { 'current_user': "alex", 'user_list': ['alex','eric'], 'user_dict': {'k1': 'v1', 'k2': 'v2'}}) index.html <html> .. <body> <div>{{current_user}}</div> <a> {{ user_list.1 }} </a> # 取列表 <a> {{ user_dict.k1 }} </a> # 取字典 <a> {{ user_dict.k2 }} </a> </body> </html> ###### 條件 def func(request): return render(request, "index.html", { 'current_user': "alex", "age": 18, 'user_list': ['alex','eric'], 'user_dict': {'k1': 'v1', 'k2': 'v2'}}) index.html <html> .. <body> <div>{{current_user}}</div> <a> {{ user_list.1 }} </a> <a> {{ user_dict.k1 }} </a> <a> {{ user_dict.k2 }} </a> {% if age %} <a>有年齡</a> {% if age > 16 %} <a>老</a> {% else %} <a>少</a> {% endif %} {% else %} <a>無年齡</a> {% endif %} </body> </html>

轉載于:https://www.cnblogs.com/weiwu1578/articles/8343610.html

總結

以上是生活随笔為你收集整理的Django安装使用基础的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。