项目需求
用户分为学生,老师,班级。
管理员登陆后可以对这些用户进行增删改查。
数据库设计分析
学生与班级-------------------多对一
老师与班级-------------------多对多
开始项目
1 创建Django项目user_manager,添加app01应用
2 配置setting.py
取消csrf验证,配置静态文件路径和session
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '0@&cx)%n!@x9u6-7pj+-y$dow1#&boejv#wo(gf$-sv_^(2enc'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'app01.apps.App01Config',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
#取消csrf验证
#'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'user_manager.urls'
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 = 'user_manager.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators
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',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/
STATIC_URL = '/static/'
#配置静态文件路径
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
#配置session
SESSION_ENGINE = 'django.contrib.sessions.backends.db' # 引擎(默认)
SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认)
SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认)
SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认)
SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认)
SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认)
SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认)
3 表设计(app01下的models.py)
班级表,学生表,老师表,管理员表
from django.db import models
class Classes(models.Model):
caption = models.CharField(max_length=32)
class Student(models.Model):
name = models.CharField(max_length=32)
email = models.CharField(max_length=32,null=True)
cls = models.ForeignKey('Classes',on_delete=None)
class Teacher(models.Model):
name = models.CharField(max_length=32)
cls = models.ManyToManyField('Classes')#这里会自动生成第三张表
class Administrator(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
4 生成表
打开Terminal,执行
python manage.py makemigrations
python manage.py migrate
5 查看生成的表
点击pycharm右上角Database,将项目下的db.sqlite3拖入进去,就可以看到了。
6 登录功能
login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
label{
width: 80px;
text-align: right;
display: inline-block;
}
</style>
</head>
<body>
<form action="login.html" method="post">
<div>
<label for="user">用户名:</label>
<input id="user" type="text" name="user" />
</div>
<div>
<label for="pwd">密码:</label>
<input id="pwd" type="password" name="pwd" />
</div>
<div>
<label> </label>
<input type="submit" value="登录" />
<span style="color: red;">{{ msg }}</span>
</div>
</form>
</body>
</html>
views.py
# Create your views here.
from django.shortcuts import render,redirect,HttpResponse
from app01 import models
def login(request):
message = ""
v = request.session
print(type(v))
from django.contrib.sessions.backends.db import SessionStore
if request.method == "POST":
user = request.POST.get('user')
pwd = request.POST.get('pwd')
c = models.Administrator.objects.filter(username=user, password=pwd).count()
if c:
request.session['is_login'] = True
request.session['username'] = user
rep = redirect('/index.html')
return rep
else:
message = "用户名或密码错误"
obj = render(request,'login.html', {'msg': message})
return obj
def logout(request):
request.session.clear()
return redirect('/login.html')
#装饰器
def auth(func):
def inner(request, *args, **kwargs):
is_login = request.session.get('is_login')
if is_login:
return func(request, *args, **kwargs)
else:
return redirect('/login.html')
return inner
@auth
def index(request):
current_user = request.session.get('username')
return render(request, 'index.html',{'username': current_user})
urls.py
from django.contrib import admin
from django.urls import path,re_path
from app01 import views
urlpatterns = [
path('admin/', admin.site.urls),
path('login.html', views.login),
path('index.html', views.index),
path('logout.html', views.logout),
]
模板页面
base.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
body{
margin: 0;
}
.hide{
display: none;
}
.menu .item{
display: block;
padding: 5px 10px;
border-bottom: 1px solid #dddddd;
}
.menu .item:hover{
background-color: black;
color: white;
}
.menu .item.active{
background-color: black;
color: white;
}
.modal{
position: fixed;
top: 50%;
left: 50%;
width: 500px;
height: 400px;
margin-top: -250px;
margin-left: -250px;
z-index: 100;
background-color: white;
}
.remove{
position: fixed;
top: 50%;
left: 50%;
width: 400px;
height: 200px;
margin-top: -100px;
margin-left: -200px;
z-index: 100