WEB框架
MVC
Model View Controller
數據庫 模板文件 業務處理
MTV
Model Template View (Django)
數據庫 模板文件 業務處理
安裝Django :pip3 install django# 創建Django工程
django-admin startproject mysite 【工程名稱】mysite
- mysite # 對整個程序進行配置
- init
- settings # 配置文件
- url # URL對應關係
- wsgi # 遵循WSIG規範,uwsgi + nginx
- manage.py # 管理Django程序:
- python manage.py
- python manage.py startapp cmdb 【創建App】
- python manage.py startapp openstack 【創建App】
- python manage.py makemigrations
- python manage.py migrate
app:
migrations 數據修改表結構
admin Django爲我們提供的後臺管理
apps 配置當前app
models ORM,寫指定的類 通過命令可以創建數據庫結構
tests 單元測試
views 業務代碼
1. 創建Django工程
django-admin startproject 工程名
2. 創建APP
cd 工程名
python manage.py startapp cmdb
3、靜態文件
project.settings.py
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
4、模板路徑
DIRS ==> [os.path.join(BASE_DIR,'templates'),]
5、settings中
middlerware
# 註釋 csrf
6、定義路由規則
url.py
"login" --> 函數名
7、定義視圖函數
app下views.py
def 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')
8、模板渲染
特殊的模板語言
-- {{ 變量名 }}
def func(request):
return render(request, "index.html", {'current_user': "alex"})
index.html
<html>
..
<body>
<div>{{current_user}}</div>
</body>
</html>
====> 最後生成的字符串
<html>
..
<body>
<div>alex</div>
</body>
</html>
-- For循環
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>