项目需求
用户分为学生,老师,班级。
管理员登陆后可以对这些用户进行增删改查。
数据库设计分析
学生与班级-------------------多对一
老师与班级-------------------多对多
开始项目
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 = TrueALLOWED_HOSTS = []# Application definitionINSTALLED_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/#databasesDATABASES = { '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-validatorsAUTH_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 = TrueUSE_L10N = TrueUSE_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'),)#配置sessionSESSION_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 modelsclass 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
复制代码Title
views.py
# Create your views here.from django.shortcuts import render,redirect,HttpResponsefrom app01 import modelsdef 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 objdef 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@authdef index(request): current_user = request.session.get('username') return render(request, 'index.html',{ 'username': current_user})urls.pyfrom django.contrib import adminfrom django.urls import path,re_pathfrom app01 import viewsurlpatterns = [ path('admin/', admin.site.urls), path('login.html', views.login), path('index.html', views.index), path('logout.html', views.logout),]复制代码
模板页面 base.html
Title {% block css %} {% endblock %}用户名:{ { username }} | 注销{% block js %} {% endblock %}复制代码{% block content %} {% endblock %}
主页index.html
{% extends "base.html" %}{% block css %}{% endblock %}{% block content %}欢迎使用时尚时尚最时尚的用户管理中心
{% endblock %}{% block js %}{% endblock %}复制代码
启动项目,自己在数据库添加一个管理员用户,登录测试。