Django筆記1

建立第一個Django專案

django-admin startproject mysite
python manage.py runserver 127.0.0.1:8080

返回靜態頁面

urls.py

views.py

settings.py

login.html

commoms.css

post

views.py:

from django.shortcuts import render, redirect
# Create your views here.
def login(req):
if req.method == "GET":
print(req.method)
return render(req, "login.html")
else:
print(req.POST)
u = req.POST.get('username')
p = req.POST.get('pwd')
print(u, p)
if u == "yanpeng" and p == "1314":
return redirect("https://www.baidu.com/")
else:
return render(req, "login.html")

login.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/commons.css"/>
</head>
<body>
<h1>使用者登入</h1>
<form method="post" action="/login/">
<input type="text" name="username" />
<input type="password" name="pwd" />
<input type="submit" value="登陸" />
</form>
</body>
</html>

get傳參

模板標記:
urls.py

from django.contrib import admin
from django.urls import path
from blog import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.login),
path('index/', views.index),
]

views.py

from django.shortcuts import render, redirect
# Create your views here.
def login(req):
if req.method == "GET":
print(req.GET)
#print(req.method)
return render(req, "login.html")
else:
print(req.POST)
u = req.POST.get('username')
p = req.POST.get('pwd')
print(u, p)
if u == "yanpeng" and p == "1314":
return redirect("/index/")
else:
return render(req, "login.html", {'msg': '使用者名稱或密碼錯誤'})
def index(req):
return render(req, "index.html", {'name': "Allen", 'users': ["a", "b", "c"]})

index.html

<h1>模版標記</h1>
<p>{{ name }}</p>
<p>{{ users }}</p>
<p>{{ users.0 }}</p>
<p>{{ users.1 }}</p>
def index(req):
return render(req, "index.html", {'name': "Allen", 'users': ["a", "b", "c"], 'dict': {"k1": "kkkk1", "k2": "kkkk2"}})
<h1>模版標記</h1>
<p>{{ name }}</p>
<p>{{ users }}</p>
<p>{{ users.0 }}</p>
<p>{{ users.1 }}</p>
<h1>字典</h1>
<p>{{ dict.k1 }}</p>
<p>{{ dict.k2 }}</p>
<h1>迴圈</h1>
{% for item in dict %}
{{ item }}
{% endfor %}
<hr />
{% for item in users %}
{{ item }}
{% endfor %}