欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Django 练习班级管理系统四 -- 编辑班级

程序员文章站 2022-03-20 20:58:22
修改 classes.html 修改 urls.py 修改 views.py 在 templates 文件夹下添加 edit_classes.html 通过 ajax 方式来更新操作 通过 url 的方式来更新操作 ......

修改 classes.html

{% extends "layout.html" %}

{% block css %}
{% endblock %}

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

    <div class="pagination">
        {{ str_pager|safe }}
    </div>

    <div class="modal hide">
        <form method="post" action="/classes.html">
            <input name="id" type="text" class="hide">
            <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');

            bindaddevent();
            bindcancelevent();
            bindtddeleteevent();
            bindsubmitmodal();
            bindtdeditevent();
        })

        submit_url = null;

        function bindaddevent() {
            $('#id_add').click(function () {
                $('.modal, .shade').removeclass('hide');
                submit_url = "/classes.html";
            })

        }

        function bindcancelevent() {
            $('#id_modal_cancel').click(function () {
                $('.modal, .shade').addclass('hide')
            })

        }

        function bindtdeditevent() {
            // 使用 js 的事件绑定委托
            $('tbody').on('click', '.td-edit', function () {
                $('.modal, .shade').removeclass('hide')
                submit_url = "/up_classes.html";
                var tds = $(this).parent().prevall();
                //console.log(tds)
                //console.log(tds[0])
                //$('.modal input[name="id"]').val()
                /*
                $('.modal input[name="caption"]').val(tds[0].innertext);
                $('.modal input[name="id"]').val(tds[1].innertext);
                */
                $(this).parent().prevall().each(function () {
                    var text = $(this).text();
                    var name = $(this).attr('klvchen');
                    //console.log(text)
                    //console.log(name)
                    $('.modal input[name="'+ name +'"]').val(text)

                })
            })
        }

        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 nid = $('.modal input[name="id"]').val();
                var value = $('.modal input[name="caption"]').val();
                submit_url = "/classes.html"
                $.ajax({
                    url: submit_url,
                    type: 'post',
                    data: {caption: value, id: nid},
                    datatype: "json",
                    success: function (rep) {
                        if(!rep.status){
                            alert(rep.error)
                        }else{
                            // 通过刷新整个界面来显示新数据
                            location.reload();

                        }
                    }
                })
                
            })

        }

    </script>
{% endblock %}

修改 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('add_classes.html', views.handle_add_classes),
    path('edit_classes.html', views.handle_edit_classes),
    path('student.html', views.handle_student),
    path('teacher.html', views.handle_teacher),
]

修改 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


def outer(func):
    def inner(request, *args, **kwargs):
        print(request.method)
        return func(request, *args, **kwargs)
    return inner


class login(views.view):
    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:
            request.session['is_login'] = true
            request.session['username'] = user
            rep = redirect('/index.html')
            return rep
        else:
            message = "用户名或密码错误"
            return render(request, 'login.html', {'msg': message})


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


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')
        # 获取所有的班级列表
        # for l in range(1, 102):
        #     models.classes.objects.create(caption='全栈一班%i' %(l))

        current_page = request.get.get('p', 1)
        current_page = int(current_page)

        # 所有数据的个数
        total_count = models.classes.objects.all().count()

        from utils.page import pagerhelper
        obj = pagerhelper(total_count, current_page, '/classes.html', 10)
        pager = obj.pager_str()

        cls_list = models.classes.objects.all()[obj.db_start:obj.db_end]

        return render(request,
                      'classes.html',
                      {'username': current_user, 'cls_list': cls_list, 'str_pager': pager})

    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 = request.post.get('caption', none)

        # 判断是更新或者是添加操作
        nid = request.post.get('id', none)

        # 更新操作
        if nid and caption:
            obj = models.classes.objects.filter(id=nid).update(caption=caption)
            # print(nid)
            # print(caption)
            response_dict['data'] = {'id': nid, 'caption': caption}
        # 添加操作
        elif caption:
            obj = models.classes.objects.create(caption=caption)
            # print(obj.id)
            # print(obj.caption)
            response_dict['data'] = {'id': obj.id, 'caption': obj.caption}
        else:
            response_dict['status'] = false
            response_dict['error'] = "标题不能为空"
        return httpresponse(json.dumps(response_dict))


@auth
def handle_add_classes(request):
    message = ""
    if request.method == 'get':
        return render(request, 'add_classes.html', {'msg': message})
    elif request.method == 'post':
        caption = request.post.get('caption')
        if caption:
            models.classes.objects.create(caption=caption)
        else:
            message = '标题不能为空'
            return render(request, 'add_classes.html', {'msg': message})
        return redirect('/classes.html')
    else:
        return redirect('/index.html')


# 通过url进行更新操作
@auth
def handle_edit_classes(request):
    if request.method == "get":
        nid = request.get.get('nid')
        obj = models.classes.objects.filter(id=nid).first()
        return render(request, 'edit_classes.html', {'obj': obj})
    elif request.method == "post":
        nid = request.post.get('nid')
        caption = request.post.get('caption')
        models.classes.objects.filter(id=nid).update(caption=caption)
        return redirect('/classes.html')
    else:
        return redirect('/index.html')


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')

在 templates 文件夹下添加 edit_classes.html

{% extends "layout.html" %}

{% block css %}
{% endblock %}

{% block content %}
    <h1>编辑班级</h1>
    <form action="/edit_classes.html" method="post">
        <input class="hide" type="text" name="nid" value="{{ obj.id }}">
        <input type="text" name="caption" value="{{ obj.caption }}">
        <input type="submit" value="提交">
    </form>
{% endblock %}


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

通过 ajax 方式来更新操作
Django 练习班级管理系统四 -- 编辑班级

通过 url 的方式来更新操作
Django 练习班级管理系统四 -- 编辑班级