1.安装环境
pip install django(有网)
python setup.py install
2.创建项目和运行项目
1)pycharm社区版的创建项目中没有Django入口,只有专业版才有
社区版可以通过命令
django工程:django-admin startproject mysite(工程名)
工程目录:
mysite/
manage.py: 一个实用的命令行工具,可让你以各种方式与该 Django 项目进行交互。
mysite/
__init__.py:该文件默认是空的,只用定义了这个文件,python虚拟机才会认为当前文件夹是一个合法的package,代表目录下面的Python程序是module的一部分。所以它是package的标识
settings.py:包括app路径,数据库配置,sql语句,静态文件目录,中间件,session存储的相关配置
urls.py: 所有网址的入口,会关联到views中的函数
wsgi.py: 是设置环境的默认值。Wsgi:Web Server Gateway Interface, 只是一种规范,描述web server与web application通信的规范,简单理解是一个配置文件,建立服务器与django程序之间的桥梁。网络通信接口
2)运行项目:
移动到mysite目录下:cd mysite
执行: python manage.py runserver
打开浏览器输入网址:http://127.0.0.1:8000/,如显示如下界面表示启动成功:)
3)Pycharm添加运行 python manage.py runserver 的快捷方式
Run-->Edit Configurations---点击+,给python添加manage标签,同时添加Script path和Parameters
3.创建和运行app
3.1创建app
python manage.py startapp bbs(app名称)
目录结构:
1.Admin.py: django 自带admin后面管理,将models.py 中表映射到后台
2.Apps.py:应用的相关配置
3.Models.py:用于设计数据库表
4.Tests.py:用于编写Django单元测试
5.Views.py:视图文件,处理用户发出的请求,从urls.py中对应过来, 通过渲染templates中的网页可以将显示内容,用户请求的数据,输出到网页
3.2 运行app
1.应用注册:新建好之后我们就要开始做项目了,首先我们要在容器Djangoproject中更改settings.py中的INSTALLED_APPS,要将我们新建的APP(myapp)加入到其中。
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
#新创建的app名称
'myapp',
]
2.在app中的views.py中加入具体请求的处理,处理业务逻辑
from django.shortcuts import render
from django.shortcuts import HttpResponse
# Create your views here.
def Login(request):
return HttpResponse("this is login")
3.在项目的urls.py中将url映射到相应的业务处理逻辑
from myapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login/', views.Login),
]
4. python manage.py runserver运行项目,打开http://127.0.0.1:8000/login/查看执行结果
3.3创建post请求
1.在项目下创建templates目录,新建login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<form action="/login/" method="post">
<h1>用户名:<input name="username"></h1>
<h1>密码:<input name="password"></h1>
<input type="submit" value="登录"></input>
</form>
</body>
</html>
2.在views.py中修改业务逻辑
from django.shortcuts import HttpResponse
from django.shortcuts import render
# Create your views here.
def Login(request):
# POST不能是小写
if request.method == "POST":
username = request.POST.get("username")
#接收html界面的提交
return HttpResponse(username)
else:
#加载html界面
return render(request,"login.html")
如果此时运行项目会报错
TemplateDoesNotExist at /login/
login.html
Request Method: GET
Request URL: http://127.0.0.1:8000/login/
Django Version: 3.1.5
Exception Type: TemplateDoesNotExist
Exception Value:
login.html
Exception Location: C:\Users\y\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\loader.py, line 19, in get_template
Python Executable: C:\Users\y\AppData\Local\Programs\Python\Python39\python.exe
Python Version: 3.9.1
Python Path:
['C:\\Users\\y\\PycharmProjects\\mysite',
'C:\\Users\\y\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\y\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\y\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\y\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\Users\\y\\AppData\\Local\\Programs\\Python\\Python39\\lib\\site-packages']
Server time: Wed, 03 Feb 2021 06:24:35 +0000
Template-loader postmortem
Django tried loading these templates, in this order:
Using engine django:
django.template.loaders.app_directories.Loader: C:\Users\y\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\templates\login.html (Source does not exist)
django.template.loaders.app_directories.Loader: C:\Users\y\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\templates\login.html (Source does not exist)
3.接下来我们需要向Django说明模板文件的路径,修改settings.py,修改 TEMPLATES 中的 DIRS 为 [os.path.join(BASE_DIR, 'templates')],在settings.py中添加
(可以解决上面的TemplateDoesNotExist 报错)
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',
],
},
},
]
4.运行项目python manage.py runserver 127.0.0.1:8000/login/
5.点击登录,会报错
解决办法:
在settings.py中注释
'django.middleware.csrf.CsrfViewMiddleware',
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
3.4 创建get请求
1、修改login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body >
<form action="/login/" method="get">
<h1>用户名:<input name="username"></h1>
<h1>密码:<input name="password"></h1>
<input type="submit" value="登录"></input>
</form>
</body>
</html>
2、修改views.py的逻辑
from django.shortcuts import HttpResponse
from django.shortcuts import render
import json
# Create your views here.
def Login(request):
if request.method == "POST":
username = request.POST.get("username")
#接收html界面的提交
return HttpResponse(username)
elif request.method == "GET":
result = {}
username = request.GET.get("username")
mobile = request.GET.get("mobile")
data = request.GET.get("data")
result["username"] = username
result["mobile"] = mobile
result["data"] = data
result = json.dumps(result)
return HttpResponse(result)
else:
#加载html界面
return render(request,"login.html")
3.查看运行结果,返回的是json字符串
但是此时的Fiddler中返回的可能是html需要给
return HttpResponse(result,content_type="application/json;charset=utf-8")
添加格式才会返回json