Django安装简介
1.Django语句
下载Django
pip install django==1.11.9
创建一个项目:firstblood
django-admin startproject firstblood
运行项目:
python manage.py runserver
python manage.py runserver 127.0.0.1:8080
# 指定IP端口运行项目
创建应用:app01
python manage.py startapp app01
运行项目出现错误:'str' and 'str'
File "D:Django练习djangoProject1djangoProject1settings.py", line 58, in <module>
'DIRS': [BASE_DIR / 'templates']
TypeError: unsupported operand type(s) for /: 'str' and 'str'
解决办法;
'DIRS': [BASE_DIR / 'templates']中的'/' 换成逗号','就可以了
2.登陆认证示例:
urls.py
from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^login/', views.login),
]
views.py
from django.shortcuts import render , HttpResponse
# Create your views here.
def login(request): #请求相关信息
if request.method == 'GET': #如果请求方法是get返回页面
print(request.method) #请求方法 GET
print(request.path) #请求路径 /login/
# return HttpResponse('hello world') #返回字符串
return render(request,'login.html') #返回页面
else:
print(request.POST)
#<QueryDict: {'username': ['root'], 'password': ['123']}>
#获取页面提交的数据
username = request.POST.get('username') #root
pwd = request.POST.get('password') #123
if username == 'jia' and pwd == '123':
return render(request,'home.html') #用户名密码正确返回home页面
return render(request, 'login.html') #否则返回登陆页面
templates目录下两个文件:
login.html
<body>
{#action属性写的是数据提交到的路径 /login/相对路径相当于 http://127.0.0.1:8000/login/#}
<form action="/login/" method="post">
用户名:<input type="text" name="username">
<br>
密码:<input type="password" name="password">
<br>
<input type="submit">
</form>
</body>
home.html
<body>
<h1>欢迎回家</h1>
</body>
访问网页出现:Forbidden (403)
解决办法:
到settings.py文件中把 MIDDLEWARE配置中的
'django.middleware.csrf.CsrfViewMiddleware',
注释掉