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

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

转载声明:转载请注明出处,本技术博客是本人原创文章

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> 项目实战-后台管理系统(一)

点击上方”python宝典”,关注获取python全套视频,

技术文章第一时间送达!

项目需求

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

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

数据库设计分析

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

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

开始项目

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"
    titleTitle/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"
    titleTitle/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

 extends "base.html" %}
 block css %}
 endblock %}
 block content %}
    h1欢迎使用时尚时尚最时尚的用户管理中心/h1
 endblock %}
 block js %}
 endblock %}

启动项目,自己在数据库添加一个管理员用户,登录测试。

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

遇到问题欢迎加小编微信一起讨论

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

识别图中二维码,欢迎关注python宝典

本人花费半年的时间总结的《Java面试指南》已拿腾讯等大厂offer,已开源在github ,欢迎star!

转载声明:转载请注明出处,本技术博客是本人原创文章

本文GitHub https://github.com/OUYANGSIHAI/JavaInterview 已收录,这是我花了6个月总结的一线大厂Java面试总结,本人已拿大厂offer,欢迎star

原文链接:blog.ouyangsihai.cn >> 项目实战-后台管理系统(一)


 上一篇
Django进阶 Django进阶
点击上方”python宝典”,关注获取python全套视频, 技术文章第一时间送达! Formdjango中的Form一般有两种功能: 输入html 验证用户输入 import re from django import forms fr
2021-04-05
下一篇 
Python生成随机验证码 Python生成随机验证码
点击上方”python宝典”,关注获取python全套视频, 技术文章第一时间送达! Python生成随机验证码,需要使用PIL模块. 安装:pip3 install pillow 基本使用 创建图片 from PIL import
2021-04-05