项目实战-后台管理系统(一)

项目需求

用户分为学生,老师,班级。

管理员登陆后可以对这些用户进行增删改查。

 

数据库设计分析

学生与班级-------------------多对一

老师与班级-------------------多对多

 

开始项目

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;
           background-color: #c00;
       }
       .shade{
           position: fixed;
           top: 0;
           left: 0;
           right: 0;
           bottom: 0;
           background-color: black;
           opacity: 0.5;
           z-index: 99;
       }
       .pagination a{
           display: inline-block;
           padding: 5px;
       }
       .pagination a.active{
           background-color: black;
           color: white;
       }
   </style>
   {% block css %} {% endblock %}
</head>
<body>
   <div style="height: 48px;background-color: black;color: white">
       <div style="float: right">用户名:{{ username }}  | <a href="/logout.html">注销</a></div>
   </div>

   <div>
       <div class="menu" style="position: absolute;top: 48px;left: 0;bottom:0;width: 200px;background-color: #eeeeee">
           <a id="menu_class" class="item" href="/classes.html">班级管理</a>
           <a id="menu_student" class="item" href="/student.html">学生管理</a>
           <a id="menu_teacher" class="item" href="/teacher.html">老师管理</a>
       </div>
       <div style="position: absolute;top: 48px;left: 200px;bottom:0;right: 0;overflow: auto">

           {% block content %} {% endblock %}

       </div>
   </div>
   <script src="/static/jquery-2.1.4.min.js"></script>
    {% block js %} {% endblock %}
</body>
</html>
主页index.html
{% extends "base.html" %}
{% block css %}
{% endblock %}
{% block content %}
   <h1>欢迎使用时尚时尚最时尚的用户管理中心</h1>
{% endblock %}
{% block js %}
{% endblock %}

 

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值