简易的学生管理系统框架

文章目录

  • base.html代码
  • students.html代码
  • student_edit代码
  • views.py代码
  • urls.py代码
  • base.css代码
  • 效果图
  • 异常
  • 分页
    • 手动分页
    • 内置分页

base.html代码

  • 在http://www.bootcss.com/找模板和渲染

      {% load static %}
      
      
        
          
          
          
          
          
          {% block title %}Dashboard Template for Bootstrap{% endblock %}
          
      	
            
            
        
        
          
          

    {%block section %}Section title{% endblock %}

    {% block content %}
    # Header Header Header Header
    1,001 Lorem ipsum dolor sit
    1,002 amet consectetur adipiscing elit
    1,003 Integer nec odio Praesent
    1,003 libero Sed cursus ante
    1,004 dapibus diam Sed nisi
    1,005 Nulla quis sem at
    1,006 nibh elementum imperdiet Duis
    1,007 sagittis ipsum Praesent mauris
    1,008 Fusce nec tellus sed
    1,009 augue semper porta Mauris
    1,010 massa Vestibulum lacinia arcu
    1,011 eget nulla Class aptent
    1,012 taciti sociosqu ad litora
    1,013 torquent per conubia nostra
    1,014 per inceptos himenaeos Curabitur
    1,015 sodales ligula in libero
    {% endblock %}

students.html代码

	{% extends 'students/base.html' %}
	{% block title %}学生列表{% endblock %}
	{% block link %}{% endblock %}
	{% block section %}{{section}}{% endblock %}
	{% block content %}
	
添加 重置
{% for stu in students %} {% endfor %}
序号 姓名 年龄 性别 qq 电话 操作
{{forloop.counter}} {{stu.name}} {{stu.age}} {{stu.gender}} {{stu.qq|default:'未填'}} {{stu.phone|default:'未填'}} 编辑 删除
{% endblock %}

student_edit代码

	
	{% extends 'students/base.html' %}
	{% block title %}添加学生{% endblock %}
	{% block section %}{{section}}{% endblock %}
	{% block content %}
	
{% csrf_token %}
{% endblock %}

views.py代码

	from django.shortcuts import render,redirect,reverse
	from django.http import HttpResponse,JsonResponse
	from django.template.loader import get_template
	from datetime import datetime
	import os
	from django_test.settings import UPLOAD_ROOT
	from students.models import Student,Grade,StudentDetail
	from django.db.models import Q
	def students(request):		#主页面,students页面
	    section = '学生列表'
	    # 获取查询参数
	    search = request.GET.get('search','').strip()
	    if search:
	        if search.isdigit():
	            # 是qq或者电话号码
	            sts = Student.objects.filter(Q(qq=search)|Q(phone=search),is_deleted=False).order_by('-e_time')
	        else:   # 说明是姓名
	            sts = Student.objects.filter(name__contains=search,is_deleted=False).order_by('-e_time')
	    else:
	        sts = Student.objects.filter(is_deleted=False).order_by('-e_time')
	    return render(request,'students/students.html',context={'students':sts,'section':section,'search':search})
	def delete_student(request):		#删除方法
	    pk = request.GET.get('pk',None)
	    if pk:
	        student = Student.objects.get(pk=pk)
	        student.is_deleted = True
	        student.save()
	    return redirect(reverse('students:students'))
	def add_student(request):		#添加页面
	    section = '添加学生'
	    grades = Grade.objects.all()
	    if request.method == 'GET':
	        return render(request,'students/student_edit.html',context={
	            'section':section,
	            'grades':grades,
	        })
	    if request.method == 'POST':
	        data = {
	            'name':request.POST.get('name'),
	            'age':request.POST.get('age'),
	            'gender':request.POST.get('gender'),
	            'qq':request.POST.get('qq'),
	            'phone':request.POST.get('phone'),
	            'grade_id':request.POST.get('grade'),
	        }
	        student = Student(**data)
	        student.save()
	        student_detail = StudentDetail(
	            num = request.POST.get('num'),
	            college = request.POST.get('college'),
	            student=student
	        )
	        student_detail.save()
	        return redirect(reverse('students:students'))
	def edit_student(request,pk):		#编辑页面
	    student = Student.objects.get(pk=pk)
	    grades = Grade.objects.all()
	    if request.method == 'GET':
	        return render(request,'students/student_edit.html',context={
	            'student':student,
	            'grades':grades,
	        })
	    if request.method == 'POST':
	        student.name = request.POST.get('name')
	        student.age = request.POST.get('age')
	        student.qq = request.POST.get('qq')
	        student.gender = request.POST.get('gender')
	        student.phone = request.POST.get('phone')
	        student.grade_id = request.POST.get('grade')
	        student.save()
	        #判断一下,student有没有详情,如果没有,创建一个
	        try:
	            student_detail = student.studentdetail
	        except:
	            student_detail = StudentDetail()
	            student_detail.student = student
	        student_detail.num = request.POST.get('num')
	        student_detail.college = request.POST.get('college')
	        student.studentdetail.save()
	        return redirect(reverse('students:students'))

urls.py代码

	from django.urls import path, re_path
	from students import views
	app_name = 'students'
	urlpatterns = [
	    path('index/', views.index, name='index'),
	    path('detail//',views.detail, name='aaa'),
	    path('login/',views.login,name='login'),
	    path('upload/',views.upload, name='upload'),
	    path('students_api/',views.students_api,name='students_api'),
	    path('students/',views.students,name='students'),
	    path('delete/',views.delete_student,name='delete'),
	    path('add/',views.add_student,name='add'),
	    path('edit//',views.edit_student,name='edit'),
	]

base.css代码

  • 通过模板查到的渲染

      /*
       * Base structure
       */
      /* Move down content because we have a fixed navbar that is 50px tall */
      body {
        padding-top: 50px;
      }
      /*
       * Global add-ons
       */
      .sub-header {
        padding-bottom: 10px;
        border-bottom: 1px solid #eee;
      }
      /*
       * Top navigation
       * Hide default border to remove 1px line.
       */
      .navbar-fixed-top {
        border: 0;
      }
      /*
       * Sidebar
       */
      /* Hide for mobile, show later */
      .sidebar {
        display: none;
      }
      @media (min-width: 768px) {
        .sidebar {
          position: fixed;
          top: 51px;
          bottom: 0;
          left: 0;
          z-index: 1000;
          display: block;
          padding: 20px;
          overflow-x: hidden;
          overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
          background-color: #f5f5f5;
          border-right: 1px solid #eee;
        }
      }
      /* Sidebar navigation */
      .nav-sidebar {
        margin-right: -21px; /* 20px padding + 1px border */
        margin-bottom: 20px;
        margin-left: -20px;
      }
      .nav-sidebar > li > a {
        padding-right: 20px;
        padding-left: 20px;
      }
      .nav-sidebar > .active > a,
      .nav-sidebar > .active > a:hover,
      .nav-sidebar > .active > a:focus {
        color: #fff;
        background-color: #428bca;
      }
      /*
       * Main content
       */
      .main {
        padding: 20px;
      }
      @media (min-width: 768px) {
        .main {
          padding-right: 40px;
          padding-left: 40px;
        }
      }
      .main .page-header {
        margin-top: 0;
      }
      /*
       * Placeholder dashboard ideas
       */
      .placeholders {
        margin-bottom: 30px;
        text-align: center;
      }
      .placeholders h4 {
        margin-bottom: 0;
      }
      .placeholder {
        margin-bottom: 20px;
      }
      .placeholder img {
        display: inline-block;
        border-radius: 50%;
      }
    

效果图

  • 主界面
    简易的学生管理系统框架_第1张图片
  • 搜索界面
    简易的学生管理系统框架_第2张图片
    添加界面
    简易的学生管理系统框架_第3张图片
  • 修改界面
    简易的学生管理系统框架_第4张图片

异常

  • 运行时出现如下报错,找了好久没找到问题
    简易的学生管理系统框架_第5张图片
  • 后来在开发者知识库找到这个贴,再次查看
    简易的学生管理系统框架_第6张图片
  • 原来自己也犯这样的错误,college被错打成collage,改正后成功
    简易的学生管理系统框架_第7张图片

分页

手动分页

  • students.html部分代码:

      
  • views.py的students的代码修改为:

      def students(request):
          section = '学生列表'
          # 获取查询参数
          search = request.GET.get('search','').strip()
          if search:
              if search.isdigit():
                  # 是qq或者电话号码
                  sts = Student.objects.filter(Q(qq=search)|Q(phone=search),is_deleted=False).order_by('-e_time')
              else:   # 说明是姓名
                  sts = Student.objects.filter(name__contains=search,is_deleted=False).order_by('-e_time')
          else:
              sts = Student.objects.filter(is_deleted=False).order_by('-e_time')
           #当前页码
          page = request.GET.get('page',1)
          page = int(page)
          #每页显示多少数据
          per_page = request.GET.get('per_page',10)
          per_page = int(per_page)
          total_num = sts.count()
          sts = sts[(page-1)*per_page:page*per_page]
          return render(request,'students/students.html',context={'students':sts,'section':section,'search':search,'per_page':per_page,'page':page,'total_num':total_num,})
    
  • pagination.html的代码:

      
    
  • customer_tags.py代码:

      @register.inclusion_tag('students/pagination.html',takes_context=True)
      def pagination_html(context):
          num =3  #总共显示多少页码
          page_num = context['page']
          per_page = context['per_page']
          students = context['students']
          total_num = context['total_num']    #总学生数
          total_page = math.ceil(total_num/per_page)  #总页数
          #页码列表
          page_list = []
          #生成当前页以及左边的页数
          if page_num - (num-1)//2 <= 0:  #左边页数从1开始
              for i in range(page_num):
                  page_list.append(i+1)
          else:   #左边的页数应该从page_num - (num-1)//2开始
              for i in range(page_num-(num-1)//2,page_num+1):
                  page_list.append(i)
          #生成当前页右边的页数
          if page_num + (num-1)//2 >= total_page:
              for i in range(page_num+1,total_page+1):
                  page_list.append(i)
          else:
              for i in range(page_num+1,page_num+(num-1)//2+1):
                  page_list.append(i)
          return {
              'page_num_list':page_list,
              'page_num':page_num,
              'context':context,
              'total_page':total_page,
          }
    

内置分页

  • 调试:

      In [1]: from students.models import Student                                                                                            
      In [2]: from django.core.paginator import Paginator                                                                                    
      In [5]: p = Paginator(Student.objects.all().order_by('-c_time'),3)                                                                     
      In [6]: p.count            #总共多少数据                                                                                                            
      Out[6]: 1
      In [7]: Student.objects.all().count()                #总共多少数据                                                                                  
      Out[7]: 1
      In [8]: p.num_pages                  #总页数                                                                                                  
      Out[8]: 1
      In [9]: p.page_range       #页码范围                                                                                                            
      Out[9]: range(1, 2)
      In [10]: page1 = p.page(1)         #第一页的数据     索引从1开始                                                                                               
      In [11]: page1.object_list                                                                                                             
      Out[11]: ]>
      In [12]: page1.has_previous()  		#有没有上一页                                                                                                        
      Out[12]: False
      In [13]: page1.has_next()         #有没有下一页                                                                                                     
      Out[13]: False
      In [14]: page1.next_page_number()        #下一页的页码,因为目前只有第一页,所以下一页为空                                                                                              
      ---------------------------------------------------------------------------
      EmptyPage                                 Traceback (most recent call last)
       in 
      ----> 1 page1.next_page_number()
      ~/PycharmProjects/django/lib/python3.6/site-packages/django/core/paginator.py in next_page_number(self)
          162 
          163     def next_page_number(self):
      --> 164         return self.paginator.validate_number(self.number + 1)
          165 
          166     def previous_page_number(self):
      ~/PycharmProjects/django/lib/python3.6/site-packages/django/core/paginator.py in validate_number(self, number)
           47                 pass
           48             else:
      ---> 49                 raise EmptyPage(_('That page contains no results'))
           50         return number
           51 
      EmptyPage: That page contains no results
    

简易的学生管理系统框架_第8张图片

你可能感兴趣的:(django)