Django 文件说明!
目录
Django文件说明:
xiangmu
├── idea # pycharm环境
├── manage.py # 管理文件
├── templates # html 样式目录
├── static # 静态目录
├── app01 # 代码规范
├── templatetags #自定义过滤器
└── xiangmu # 项目目录
├── __init__.py
├── settings.py # 配置
├── urls.py # 路由 --> URL和函数的对应关系
└── wsgi.py # 代替socket通信,把请求相关的内容封装成request对象
HTML目录:
templates:
在进行复制页面拷贝body和head到html,将路径都修改为静态路径
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
#bootstrap.css
#login.css 都通过静态名进行引用
<link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/login.css">
</head>
<body>
<div class="container">
# form表单设置
# action提交的地址默认当前地址,method默认get请求,post提交,required=""必须要填写
# novalidate添加后不会校验
# 设置数据通过post返回给后端,设置返回地址和提交方式action="" method="post"
# email和password分别设置username和password输入值
<form class="form-signin" action="" method="post">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="email" name="username" id="inputEmail" class="form-control" placeholder="Email address" required="" autofocus="">
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" name="password" class="form-control" placeholder="Password" required="">
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
</body>
</html>
表格交互
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
<link rel="stylesheet" href="/static/css/biaoge.css">
<style>
table{
font-family: 新宋体;
font-size: 20px;
text-align: center;
line-height: 70px;
}
a{
display: inline-block;
width: 60px;
height: 50px;
line-height: 50px;
color: #e2e2e2;
border-radius: 10px;
background-color: #009688;
}
#dd{
font-size: 20px;
text-align: center;
line-height: 50px;
}
th{
text-align: center;
font-size: 25px;
}
td{
text-align: center;
font-size: 25px;
}
.waihe{
margin: 0 auto;
width: 1915px;
}
</style>
</head>
<body>
<div class="waihe">
<a id="dd" href="/publisher_add/">添加</a>
<table border="1" class="table table-striped">
<thead>
<tr>
<th>序号</th>
<th>ID</th>
<th>出版社名称</th>
<th>操作</th>
</tr>
</thead>
<tbody>
{% for publisher in all_publisher %}
<tr>
<td >{{ forloop.counter}}</td>
<td >{{ publisher.pid}}</td>
<td >{{ publisher.name}}</td>
<td >
<a href="/publisher_del/?pk={{publisher.pid}}">删除</a>
<a href="/publisher_edit/?pk={{publisher.pid}}">编辑</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</body>
</html>
表单交互:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
<style>
.waike{
margin: 0 auto;
width: 500px;
}
p{
font-weight:700;
font-size: 20px;
}
form{
font-family: 新宋体;
font-size: 20px;
line-height: 50px;
}
</style>
</head>
<body>
<form action="" method="post">
<div class="waike">
<p>班级:<input type="text" class="form-control" name="class_name" value="{{name}}">
<span style="color: red">{{error}}</span>
</p>
<p>老师:<input type="text" class="form-control" name="class_laoshi" value="{{laoshi}}"></p>
<p>课程:<input type="text" class="form-control" name="class_keming" value="{{keming}}"></p>
<p>周期:<input type="text" class="form-control" name="class_zhouqi" value="{{zhouqi}}"></p>
<button class="btn btn-success btn-lg">添加班级数据</button>
<a class="btn btn-info btn-lg" href="/class_list/" role="button">返回首页</a>
</div>
</form>
</body>
</html>
静态目录:
创建static静态目录:
css # 样式
img # 图片
js # javascrip文件
plugins #js bootstrap引用的css文件存放位置
css文件示例:
body {
padding-top: 40px;
padding-bottom: 40px;
background-color: #eee;
}
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
.form-signin .form-signin-heading,
.form-signin .checkbox {
margin-bottom: 10px;
}
.form-signin .checkbox {
font-weight: normal;
}
.form-signin .form-control {
position: relative;
height: auto;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
padding: 10px;
font-size: 16px;
}
.form-signin .form-control:focus {
z-index: 2;
}
.form-signin input[type="email"] {
margin-bottom: -1px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.form-signin input[type="password"] {
margin-bottom: 10px;
border-top-left-radius: 0;
border-top-right-radius: 0;
}
app01-代码规范:
创建app:python manage.py startapp app01 manage.py是管理项目的脚本文件
-
app01目录下文件自动生成
migrations # 创建mysql数据的迁移文件 admin.py # django admin管理后台,对数据库表进行增删改查操作 apps.py # app的信息 models.py # 模型 om跟数据库相关 tests.py # 测试使用 views.py # 视图,写函数
views.py-url 页面判断对应的函数
from django.shortcuts import HttpResponse,render,redirect
from app01 import models #打开数据库类进行调用
def index(request): #接受参数
return HttpResponse("登录成功") #返回字符串
def home(request):
return render(request,'home.html') #访问home目录,跳转到路径
def login(request):
if request.method == "GET":
return render(request, 'login.html') #返回登录页面
if request.method == "POST":
user = request.POST.get("username") #获取提交的数据
pwd = request.POST.get("password")
# ret = models.User.objects.get(username="user",password="pwd") #找不到或者一个都报错
ret = models.User.objects.filter(username=user,password=pwd) #找不到对象列表
if user == "haiyang" and pwd == "123":
return redirect("/index/") #效验成功 跳转到首页(重定向)
else:
return redirect("/login/") #效验失败,返回登录页面
models.py 命令存放
-
数据库命令存放位置
python manage.py makemigrations # 记录models.py文件更新状态 python manage.py migrate # 执行数据库的迁移命令,将sql语句提交到数据库中
-
创建表和字段
from django.db import models class Publisher(models.Model): #Publisher:表名,继承models.Model类 pid = models.AutoField(primary_key=True) #自增、主键 name = models.CharField(max_length=32,unique=True) #约束唯一 def __str__(self): return "{}{}".format(self.pid,self.name) #返回给调用者内容
项目文件:
manage.py:
-
管理配置文件
__init__
:
#使用pymysql模块连接mysql数据库
import pymysql
pymysql.install_as_MySQLdb()
settings.py 配置文件:
- 配置文件主要包含
- 设置主机访问权限
- 数据库连接配置
- html存放位置
- 静态文件(css,js,img)存放位置
import os
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #项目路径
SECRET_KEY = '0s=cn7g2p!xbd)m&6ew)!ltcf!&=t#c&=tiu*l35vt#ir5@)mz'
DEBUG = True #debug模式,前端页面会显示错误提示,关闭则不显示
ALLOWED_HOSTS = ['*'] #设置主机权限
#django默认注册的app
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions', #sessions使用app中必须要有
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config'] #注册一个新的app,推荐写法
MIDDLEWARE = [ #中间件
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware', #中间件中也要有session
'django.middleware.common.CommonMiddleware',
#'django.middleware.csrf.CsrfViewMiddleware', #提交post请求,校验功能关闭,登录403问题
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'xiangmu.urls' #路由配置文件
#存放html模板文件
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',
],
},
},
]
WSGI_APPLICATION = 'xiangmu.wsgi.application'
#数据库配置
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql', #使用mysql数据库
'NAME': 'haiyangdb', # 库名称
'HOST': '127.0.0.1', # 地址
'PORT': 3306, # 端口
'USER': 'root', # 账号
'PASSWORD': '123' # 密码
}
}
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
LANGUAGE_CODE = 'en-us' #'zh_Hans' admin中可以修改为中文,默认英文
TIME_ZONE = 'UTC' #'Asia/Shanghai' 修改时区
USE_I18N = True
USE_TZ = True
APPEND_SLASH=True
USE_L10N = False # 时间配置
DATETIME_FORMAT = 'Y-m-d H:i:s'
DATE_FORMAT = 'Y-m-d'
TIME_FORMAT = 'H:i:s'
#静态路径配置和别名
STATIC_URL = '/static/' #静态别名,样式 js 图片都是静态文件
STATICFILES_DIRS = [
os.path.join(BASE_DIR,'static'), #设置静态路径
os.path.join(BASE_DIR,'x1'), #可以设置多个图片路径,调用时都使用static就可以
os.path.join(BASE_DIR,'x2') #如果图片重名只会拿到第一个(列表顺序)
]
#在python中打印sql语句
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'handlers': {
'console':{
'level':'DEBUG',
'class':'logging.StreamHandler',
},
},
'loggers': {
'django.db.backends': {
'handlers': ['console'],
'propagate': True,
'level':'DEBUG',
},
}
}
from django.conf import global_settings #django默认全局配置
urls.py 路由:
-
路由中常用参数和方法:
#查看请求类型和数据类型 print(request.method,type(request.method)) #查看get请求 print(request.POST, type(request.POST)) #查看post请求 #参数: HttpResponse("欢迎光临") 返回字符串 render(request,'home.html') 返回目录跳转到路径 示例: redirect("/login/") 跳转到本地目录或者跳转URL
-
URL和函数对应关系
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ #调用配置文件 url(r'^admin/', admin.site.urls), url(r'^index/', views.index), url(r'^home/', views.home), url(r'^login/', views.login), url(r'^publisher_add/',views.AddPublisher.as_view() ) #调用类名 ]
wsgipy 通信:
程序人生,逆水行舟,不进则退,差则思勤