Django 练习班级管理系统一

创建项目 user_manager 和 app为 app01

models.py 为

from django.db import models

# Create your models here.


class Classes(models.Model):
    caption = models.CharField(max_length=32)


class Student(models.Model):
    name = models.CharField(max_length=32)
    cls = models.ForeignKey(Classes, on_delete=models.CASCADE)


class Teacher(models.Model):
    name = models.CharField(max_length=32)
    cls = models.ForeignKey(Classes, on_delete=models.CASCADE)


class Administrator(models.Model):
    username = models.CharField(max_length=32)
    password = models.CharField(max_length=32)

views.py 为

from django.shortcuts import render, redirect, HttpResponse


# Create your views here.
from app01 import models
from django import views
from django.utils.decorators import method_decorator


# 登录函数
class Login(views.View):
    # 可以重写 dispatch 函数,达到装饰器的效果
    def dispatch(self, request, *args, **kwargs):
        # print(11111111111)
        ret = super(Login, self).dispatch(request, *args, **kwargs)
        # print(22222222222)
        return ret


    def get(self, request, *args, **kwargs):
        print('GET')
        return render(request, 'login.html', {'msg': ''})


    def post(self, request, *args, **kwargs):
        print('POST')
        user = request.POST.get('user')
        pwd = request.POST.get('pwd')
        # 验证用户名和密码是否正确
        c = models.Administrator.objects.filter(username=user, password=pwd).count()
        if c:
            # 设置了 session
            request.session['is_login'] = True
            request.session['username'] = user
            # redirect 到 index.html 页面
            rep = redirect('/index.html')
            return rep
        else:
            # 登录失败,跳转回 login.html 页面
            message = "用户名或密码错误"
            return render(request, 'login.html', {'msg': message})

# 装饰器,用来验证用户是否登录
def auth(func):
    def inner(request, *args, **kwargs):
        # 获取 session 中的 is_login 值,没有值则跳转回 login.html 页面
        is_login = request.session.get('is_login')
        if is_login:
            return func(request, *args, **kwargs)
        else:
            return redirect('/login.html')
    return inner

# 登录后的首页,通过 session 获取 username,如果不使用装饰器就得每个方法都得写一遍验证方法。
def index(request):
    current_username = request.session.get('username')
    if current_username:
        return render(request, 'index.html', {'username': current_username})
    else:
        return redirect('/login.html')


@auth
def handle_classes(request):
    if request.method == "GET":
        current_user = request.session.get('username')
        # 插入记录
        # models.Classes.objects.create(caption='全栈一班')
        # models.Classes.objects.create(caption='全栈二班')
        # models.Classes.objects.create(caption='全栈三班')
        # 获取所有的班级列表
        cls_list = models.Classes.objects.all()
        return render(request,
                      'classes.html',
                      {'username': current_user, 'cls_list': cls_list})

    elif request.method == "POST":
        # Form 表单提交的处理方式
        """
        caption = request.POST.get('caption', None)
        models.Classes.objects.create(caption=caption)
        return redirect('/classes.html')
        """
        # Ajax 提交的方式处理
        import json
        response_dict = {'status': True, 'error': None, 'data': None}
        # 获取 caption
        caption = request.POST.get('caption', None)
        if caption:
            # 创建记录
            obj = models.Classes.objects.create(caption=caption)
            # print(obj.id)
            # print(obj.caption)
            # 返回包含 id 和 caption 的字典
            response_dict['data'] = {'id': obj.id, 'caption': obj.caption}
        else:
            response_dict['status'] = False
            response_dict['error'] = "标题不能为空"
        return HttpResponse(json.dumps(response_dict))


def handle_teacher(request):
    is_login = request.session.get('is_login')
    if is_login:
        current_user = request.session.get('username')
        return render(request, 'teacher.html', {'username':current_user})
    else:
        return redirect('/login.html')


def handle_student(request):
    is_login = request.session.get('is_login')
    if is_login:
        current_user = request.session.get('username')
        return render(request, 'student.html', {'username':current_user})
    else:
        return redirect('/login.html')

settings.py 修改

# 在 MIDDLEWARE  下注释
#'django.middleware.csrf.CsrfViewMiddleware',

# 在最后添加
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

urls.py 为

from django.contrib import admin
from django.urls import path
from app01 import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('login.html', views.Login.as_view()),
    path('index.html', views.index),
    path('classes.html', views.handle_classes),
    path('student.html', views.handle_student),
    path('teacher.html', views.handle_teacher),
]

添加一个 templates 文件夹,里面增加下面 html 文件
layout.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;
        }

        .shade{
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background-color: black;
            opacity: 0.5;
            z-index: 99;
        }

        .remove{
            position: fixed;
            top: 50%;
            left: 50%;
            width: 400px;
            height: 200px;
            margin-top: -100px;
            margin-left: -200px;
            z-index: 100;
            background-color: #cc0000;
        }
        {% block css %} {% endblock %}
    </style>
</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: #eee">
            <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.min.js"></script>

{% block js %} {% endblock %}
</body>
</html>

index.html

{% extends "layout.html" %}

{% block css %}
{% endblock %}

{% block content %}
    <h1>欢迎使用管理中心</h1>
{% endblock %}

{% block js %}
{% endblock %}

classes.html

{% extends "layout.html" %}

{% block css %}
{% endblock %}

{% block content %}
    <h1>班级管理</h1>
    <div>
        <input id="id_add" type="button" value="添加">
    </div>
    <table border="1">
        <thead>
            <tr>
                <th>ID</th>
                <th>标题</th>
            </tr>
        </thead>
        <tbody>
            {% for item in cls_list %}
                <tr>
                    <td>{{ item.id }}</td>
                    <td>{{ item.caption }}</td>
                    <td>
                        <a>编辑</a>|<a class="td-delete">删除</a>
                    </td>
                </tr>
            {% endfor %}
        </tbody>
    </table>

    <div class="modal hide">
        <form method="post" action="/classes.html">
            {% csrf_token %}
            <input name="caption" type="text" placeholder="标题">
            <input id="id_modal_cancel" type="button" value="取消">
            <input type="submit" value="确定">
            <input type="button" id="modal_ajax_submit" value="Ajax确定">
        </form>
    </div>
    <div class="shade hide"></div>
    <div class="remove hide">
        <input id="id_remove_cancel" type="button" value="取消">
        <input type="button" value="确定">
    </div>
{% endblock %}

{% block js %}
    <script>
        // 进入页面之间调用下面的方法
        $(function () {
            $('#menu_class').addClass('active');
            // 绑定 click 事件
            bindAddEvent();
            bindCancelEvent();
            bindTdDeleteEvent();
            bindSubmitModal();
        })

        function bindAddEvent() {
            $('#id_add').click(function () {
                $('.modal, .shade').removeClass('hide')
            })

        }

        function bindCancelEvent() {
            $('#id_modal_cancel').click(function () {
                $('.modal, .shade').addClass('hide')
            })

        }


        function bindTdDeleteEvent() {
            /* 新建的 td 没有绑定 click 事件
            $('td .td-delete').click(function () {
                $('.remove, .shade').removeClass('hide')
            })
            */
            // 使用 js 的事件绑定委托
            $('tbody').on('click', '.td-delete', function () {
                $('.remove, .shade').removeClass('hide')
            })
        }


        function bindSubmitModal() {
            $('#modal_ajax_submit').click(function () {
                var value = $('.modal input[name="caption"]').val();
                $.ajax({
                    url: "/classes.html",
                    type: 'POST',
                    data: {caption: value},
                    dataType: "JSON",
                    // 成功返回 rep 
                    success: function (rep) {
                        if(!rep.status){
                            alert(rep.error)
                        }else{
                            // 通过刷新整个界面来显示新数据
                            //location.reload();

                            // 通过js 在 table 表格最后追加一行数据,追加的数据就是当前增加的数据
                            var tr = document.createElement('tr');
                            var td1 = document.createElement('td');
                            td1.innerHTML = rep.data.id;
                            var td2 = document.createElement('td');
                            td2.innerHTML = rep.data.caption;
                            var td3 = document.createElement('td');
                            td3.innerText = "|";
                            var a1 = document.createElement('a');
                            a1.innerHTML = "编辑";
                            var a2 = document.createElement('a');
                            a2.className = "td-delete";
                            a2.innerHTML = "删除";
                            $(td3).prepend(a1);
                            $(td3).append(a2);
                            $(tr).append(td1);
                            $(tr).append(td2);
                            $(tr).append(td3);
                            $('table tbody').append(tr);
                            $('.modal, .shade').addClass('hide');


                        }
                    }
                })
                
            })

        }

    </script>
{% endblock %}

login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="login.html" method="post">
    {% csrf_token %}
    <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>

student.html

{% extends "layout.html" %}

{% block css %}
{% endblock %}

{% block content %}
    <h1>学生列表</h1>
{% endblock %}

{% block js %}
    <script>
        $(function () {
            $('#menu_student').addClass('active');
        })
    </script>
{% endblock %}

teacher.html

{% extends "layout.html" %}

{% block css %}
{% endblock %}

{% block content %}
    <h1>老师列表</h1>
{% endblock %}

{% block js %}
    <script>
        $(function () {
            $('#menu_teacher').addClass('active');

        })
    

    </script>
{% endblock %}

创建一个 static 文件夹,把 jquery.min.js 放进去

#生成同步数据库的脚本:
python manage.py makemigrations  

#同步数据库:
python manage.py migrate

# 启动 
python manage.py runserver 8000

效果:

posted @ 2019-06-26 14:52  klvchen  阅读(811)  评论(0编辑  收藏  举报