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

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

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

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

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

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

技术文章第一时间送达!

班级管理

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"url添加/a
    /div
    table border="1"
        thead
            tr
                thID/th
                th标题/th
                th操作/th
            /tr
        /thead
        tbody
        {% if cls_list %}
            {% for item in cls_list %}
                tr
                    td alex="id"{{ item.id }}/td
                    td alex="caption"{{ item.caption }}/td
                    td
                        a class="td-edit"编辑/a| a target="_blank" href="/edit_classes.html?nid={{ item.id }}"跳转编辑/a | a class="td-delete" href="/del_classes.html?nid={{ item.id }}"删除/a
                    /td
                /tr
            {% endfor %}
        {% endif %}
        /tbody
    /table


    div class="pagination"
    {% if  str_pager%}
        {{ str_pager|safe }}
    {% endif %}
    /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="Submit确定"/
        input type="button" id="modal_ajax_submit" value="Ajax确定"/
    /form
/div
div class="shade hide"/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  bindTdEditEvent() {
            /*
            $('td .td-delete').click(function () {
                $('.remove,.shade').removeClass('hide');
            })
            */
            $('tbody').on('click', '.td-edit', function () {
                $('.modal,.shade').removeClass('hide');
                SUBMIT_URL = "/up_classes.html";
                /*
                var tds = $(this).parent().prevAll();
                $('.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('alex');
                    $('.modal input[name="' + name +'"]').val(text);
                })

            })
        }
        function  bindCancelEvent() {
            $('#id_modal_cancel,#id_remove_cancel').click(function () {
                $('.modal,.shade,.remove').addClass('hide');
            });
        }
        function bindSubmitModal() {
            $('#modal_ajax_submit').click(function () {
                var nid = $('.modal input[name="id"]').val();
                var value = $('.modal input[name="caption"]').val();
                $.ajax({
                    url: SUBMIT_URL,
                    type: 'POST',
                    data: {caption: value,id: nid},
                    dataType: "JSON",
                    success: function (rep) {
                        //data = JSON.parse(data);
                        if(!rep.status){
                            alert(rep.error);
                        }else{
                            // location.reload();
                            // 通过js在table表格最后追加一行数据,追加的数据就是当前增加的数据
                            /*
                            tr
                                td{{ item.id }}/td
                                td{{ item.caption }}/td
                                td
                                    a编辑/a | a class="td-delete"删除/a
                                /td
                            /tr
                            */
                            var tr = document.createElement('tr');
                            var td1 = document.createElement('td');
                            // td1ID
                            td1.innerHTML = rep.data.id;
                            var td2 = document.createElement('td');
                            // td2标题
                            td2.innerHTML = rep.data.caption;
                            var td3 = document.createElement('td');
                            td3.innerText = "|";
                            var a1 = document.createElement('a');
                            a1.className = "td-edit";
                            a1.innerHTML = "编辑";
                            var a11 = document.createElement('a');
                            a11.href = "/edit_classes.html?nid="+rep.data.id;
                            a11.innerHTML = "跳转编辑";
                            var a2 = document.createElement('a');
                            a2.className = "td-delete";
                            a2.href="/del_classes.html?nid="+rep.data.id;
                            a2.innerHTML = "删除";
                            $(td3).prepend(a1);
                            $(td3).append(a11);
                            $(td3).append(a2);
                            $(tr).append(td1);
                            $(tr).append(td2);
                            $(tr).append(td3);
                            $('table tbody').append(tr);
                        $('.modal,.shade').addClass('hide');
                        }
                    }
                })

            })
        }
    /script
{% endblock %}

add_classes.html


{% extends "layout.html" %}
{% block css %}
{% endblock %}
{% block content %}
    h1添加班级/h1
    form action="/add_classes.html" method="POST"
        input type="text" name="caption" /
        input type="submit" value="提交"/{{ msg }}
    /form
{% endblock %}
{% block js %}
    script
        $(function () {
            $('#menu_class').addClass('active');
        });
    /script
{% endblock %}

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 %}

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),
   path('classes.html', views.handle_classes),
   path('add_classes.html', views.handle_add_classes),
   path('edit_classes.html', views.handle_edit_classes),
   path('del_classes.html', views.handle_del_classes),
]

分页工具类

utils.page.py


#__author:  Administrator
#date:  2016/12/7

class PagerHelper:
    def __init__(self,total_count,current_page,base_url,per_page=10):
        self.total_count = total_count
        self.current_page = current_page
        self.base_url = base_url
        self.per_page = per_page

    @property
    def db_start(self):
        return (self.current_page -1) * self.per_page

    @property
    def db_end(self):
        return self.current_page * self.per_page

    def total_page(self):
        v, a = divmod(self.total_count, self.per_page)
        if a != 0:
            v += 1
        return v

    def pager_str(self):
        v = self.total_page()
        pager_list = []
        if self.current_page == 1:
            pager_list.append('a href="javascript:void(0);"上一页/a')
        else:
            pager_list.append('a href="%s?p=%s"上一页/a' % (self.base_url, self.current_page - 1,))
        # 61:12
        # 72:13
        if v = 11:
            pager_range_start = 1
            pager_range_end = v
        else:
            if self.current_page  6:
                pager_range_start = 1
                pager_range_end = 11 + 1
            else:
                pager_range_start = self.current_page - 5
                pager_range_end = self.current_page + 5 + 1
                if pager_range_end  v:
                    pager_range_start = v - 10
                    pager_range_end = v + 1

        for i in range(pager_range_start, pager_range_end):
            if i == self.current_page:
                pager_list.append('a class="active" href="%s?p=%s"%s/a' % (self.base_url, i, i,))
            else:
                pager_list.append('a href="%s?p=%s"%s/a' % (self.base_url, i, i,))

        if self.current_page == v:
            pager_list.append('a href="javascript:void(0);"下一页/a')
        else:
            pager_list.append('a href="%s?p=%s"下一页/a' % (self.base_url, self.current_page + 1,))

        pager = "".join(pager_list)
        return pager

veiws.py


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

@auth
def handle_classes(request):
    if request.method == "GET":
        # 当前页
        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',5)
        pager = obj.pager_str()
        cls_list = models.Classes.objects.all()[obj.db_start:obj.db_end]
        current_user = request.session.get('username')
        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)
        if caption:
            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)
        print(caption)
        if caption:
            obj = models.Classes.objects.create(caption=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',None)
        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')

@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')
@auth
def handle_del_classes(request):
    nid = request.GET.get('nid')
    a = models.Classes.objects.get(id=nid).delete();
    return redirect('/classes.html')

至此,班级的增删改查就完成了。

项目源码下载:链接:https://pan.baidu.com/s/1yzijy8wpA-URFu8mGAQeRw 密码:pf7f

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

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

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

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

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

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

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

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


 上一篇
文件上传三种方式 文件上传三种方式
点击上方”python宝典”,关注获取python全套视频, 技术文章第一时间送达! 需求 上传图片在页面显示 Form表单上传 !DOCTYPE html html lang="en" head meta charset="UTF
2021-04-05
下一篇 
项目实战-后台管理系统(三) 项目实战-后台管理系统(三)
点击上方”python宝典”,关注获取python全套视频, 技术文章第一时间送达! 学生管理 student.html {% extends "base.html" %} {% block css %} {% endblock %
2021-04-05