• 基于FORM组件学生管理系统【中间件】


    目的:实现学生,老师,课程的增删改查

    models.py

    from django.db import models
    
    # Create your models here.
    class UserInfo(models.Model):
        """
        用户表:既有班主任也有老师
        """
        username = models.CharField(max_length=32)
        password = models.CharField(max_length=64)
        email = models.CharField(max_length=32)
        ut = models.ForeignKey(to="UserType")  #用户和用户类型一对多的关系
        teacher_classes = models.ManyToManyField(to="Classes")  #老师和班级的多对多关系
    
    class UserType(models.Model):
        """
        用户类型表
        """
        title = models.CharField(max_length=32)
    
    class Classes(models.Model):
        """
        班级表
        """
        name = models.CharField(max_length=32)
        classteacher = models.ForeignKey(to="UserInfo")  #班级和班主任是一对多的关系
    
    
    class Student(models.Model):
        """
        学生表
        """
        name = models.CharField(max_length=32)
        age = models.IntegerField(max_length=32)
        cls = models.ForeignKey(to="Classes")  #学生和班级的一对多关系

    1、urls.py

     1 from django.conf.urls import url
     2 from django.contrib import admin
     3 from app01 import views
     4 urlpatterns = [
     5     url(r'^admin/', admin.site.urls),
     6     url(r'^login/', views.login),
     7     #老师管理
     8     url(r'^teacherindex/', views.teacherindex),
     9     url(r'^addteacher/', views.addteacher),
    10     url(r'^editteacher/(d+)', views.editteacher),
    11     url(r'^delteacher/(d+)', views.delteacher),
    12     #学生管理
    13     url(r'^studentindex/', views.studentindex),
    14     url(r'^addstudent/', views.addstudent),
    15     url(r'^delstudent/(d+)', views.delstudent),
    16     url(r'^editstudent/(d+)', views.editstudent),
    17 
    18     #班级管理
    19     url(r'^classindex/', views.classindex),
    20     url(r'^addclass/', views.addclass),
    21     url(r'^delclass/(d+)', views.delclass),
    22     url(r'^editclass/(d+)', views.editclass),
    23 
    24     #测试中间件
    25     url(r'^test', views.testMD),
    26 ]
    urls.py

    2、views.py 

      1 from django.shortcuts import render,redirect,HttpResponse
      2 from app01 import models
      3 # Create your views here.
      4 from django.forms import Form
      5 from django.forms import fields
      6 from django.forms import widgets
      7 from django.conf import settings
      8 from django.core.validators import ValidationError
      9 from django.core.validators import RegexValidator
     10 # 1、创建规则
     11 class TeacherForm(Form):  #必须继承Form
     12     # 创建字段,本质上是正则表达式
     13     username = fields.CharField(
     14         required=True,     #必填字段
     15         error_messages={"required":"用户名不能为空!!"},  #显示中文错误提示
     16         widget=widgets.TextInput(attrs={"placeholder":"用户名","class":"form-control"}),  #自动生成input框
     17         label="姓名",
     18         label_suffix=":"
     19        )
     20     password = fields.CharField(required=True, error_messages={'required': '密码不能为空'},
     21                                 widget=widgets.PasswordInput(attrs={'placeholder': '密码', 'class': 'form-control'}),
     22                                 label="密码",
     23                                 label_suffix=":"
     24       )  # 不能为空
     25 
     26     email = fields.EmailField(
     27         required=True,
     28         error_messages={"required":"邮箱不能为空!!","invalid":"无效的邮箱"},
     29         widget=widgets.EmailInput(attrs={"placeholder": "邮箱", "class": "form-control"}),  # 自动生成input框
     30         label = "邮箱",
     31         label_suffix = ":"
     32     ) #不能为空且邮箱格式要一致
     33     teacher_classes = fields.MultipleChoiceField(
     34         label="任教班级",
     35         label_suffix=":",
     36         choices=[]  #注意一定要用values_list
     37 
     38     )
     39 
     40     def __init__(self, *args, **kwargs):
     41         super().__init__(*args, **kwargs)
     42         self.fields["teacher_classes"].choices = models.Classes.objects.values_list("id", "name")
     43 
     44     def clean_name(self):
     45         name = self.cleaned_data["name"]
     46         valid = models.Student.objects.filter(name=name).first()
     47         if valid:
     48             raise ValidationError("用户名已存在")
     49         return name
     50 
     51 class LoginForm(Form):
     52     username = fields.CharField(
     53         required=True,  #必填字段
     54         min_length=3,
     55         max_length=16,
     56         error_messages={
     57             "required":"用户名不能为空",
     58             "min_length":"长度不能小于3",
     59             "max_length":"长度不能大于16"
     60         },
     61         widget=widgets.TextInput({"placeholder":"username","class":"form-control"})
     62     )
     63     password = fields.CharField(
     64         required=True,
     65         min_length=3,
     66         max_length=16,
     67         error_messages={
     68             "required": "密码不能为空",
     69             "min_length": "密码长度不能小于3",
     70             "max_length": "密码长度不能大于16",
     71             # "invalid":"密码格式错误"
     72             # error_messages的优先级高,如果写上"invalid":"密码格式错误"这个就会优先显示这个错误
     73         },
     74         widget=widgets.PasswordInput({"placeholder":"password","class":"form-control"}),
     75         validators=[RegexValidator("d+","密码只能是数字")]  #可以进行正则匹配提示错误
     76     )
     77 
     78     def clean_username(self):
     79         user = self.cleaned_data["username"]
     80         is_exits = models.UserInfo.objects.filter(username=user).count()
     81         if not is_exits:
     82             raise ValidationError("用户名和密码错误")
     83         return user   #必须有return
     84 
     85 class StudentForm(Form):  #必须继承Form
     86     # 创建字段,本质上是正则表达式
     87 
     88     name = fields.CharField(
     89         required=True,     #必填字段
     90         error_messages={"required":"姓名不能为空!!"},  #显示中文错误提示
     91         widget=widgets.TextInput(attrs={"placeholder":"姓名","class":"form-control"}),  #自动生成input框
     92        )
     93     age = fields.CharField(required=True, error_messages={'required': '年龄不能为空'},
     94                            widget=widgets.TextInput(attrs={'placeholder': '年龄', 'class': 'form-control'}),
     95       )  # 不能为空
     96     class_list = models.Classes.objects.all().values_list('id',"name")
     97     cls_id=fields.ChoiceField(choices=class_list)
     98     # 这个方法判断用户名存在不
     99     def clean_name(self):
    100         name = self.cleaned_data["name"]   #只能拿自己当前的字段值
    101         valid = models.Student.objects.filter(name=name).first()
    102         if valid:
    103             raise ValidationError("用户名已存在")  #主动报错
    104         return name   #必须有返回值
    105 
    106 class ClassesForm(Form):
    107     name = fields.CharField(
    108         required=True,  # 必填字段
    109         error_messages={"required": "姓名不能为空!!"},  # 显示中文错误提示
    110         widget=widgets.TextInput(attrs={"placeholder": "姓名", "class": "form-control"}),  # 自动生成input框
    111     )
    112     # 如果直接定义成classteacher_id,,_id 的形式,这样你添加数据的时候不会时时更新,所以在下面定义一个重写的方法
    113     # classteacher_id = fields.ChoiceField(choices= models.UserInfo.objects.filter(ut_id = settings.ROLE_CLASSTEACHER).values_list('id', "username"))
    114 
    115     classteacher_id = fields.ChoiceField(choices=[])
    116     def __init__(self,*args,**kwargs):   #重写init方法,时时更新
    117         super().__init__(*args,**kwargs)
    118         self.fields["classteacher_id"].choices = models.UserInfo.objects.filter(ut_id = settings.ROLE_CLASSTEACHER).values_list('id', "username")
    119 
    120 def login(request):
    121     if request.method == "GET":
    122         form = LoginForm()
    123         return render(request, "login.html", {"form": form})
    124     else:
    125         form = LoginForm(data=request.POST)
    126         if form.is_valid():
    127             print(form.cleaned_data)
    128             user = models.UserInfo.objects.filter(**form.cleaned_data).first()
    129             if user:  #这次是和数据库里的数据进行比较
    130                 #验证成功
    131                 print(user.username)
    132                 request.session[settings.GDP] = {"id":user.id,"username":user.username}  #设置session
    133                 return redirect("/teacherindex/")
    134             else:
    135                 #验证失败,就给增加一个错
    136                 form.add_error("password","用户名或密码不正确")
    137                 return render(request, "login.html", {"form": form})
    138         else:
    139             return render(request, "login.html", {"form": form})
    140 
    141 # 用装饰器的方法实现验证,如果是正确的用户就可以进去主页并且操作,如果不是就进不去主页,还让在登录页面上
    142 # 这个方法可以是可以,但是你的函数要是有成百上千个,那每个都加装饰器是不是就有点费事了。
    143 # 那还有一种更牛逼的方法,那就是中间件。用中间件就可以实现和装饰器一样的功能了
    144 def auth(func):
    145     def inner(request, *args, **kwargs):
    146         user_info = request.session.get("username")
    147         if not user_info:
    148             return redirect('/login/')
    149         return func(request, *args, **kwargs)
    150     return inner
    151 #老师主页面
    152 
    153 def teacherindex(request):
    154     teacher_obj = models.UserInfo.objects.filter(ut_id=1)
    155     username = request.session.get("username")
    156     return render(request,"teacherindex.html",{"teacher_obj":teacher_obj,"username":username})
    157 # 2、使用规则:将数据和规则进行匹配
    158 
    159 def addteacher(request):
    160     if request.method=="GET":
    161         form = TeacherForm()  #只是让显示一个input框
    162         return render(request, "addteacher.html", {"form":form})
    163     else:
    164         form = TeacherForm(data=request.POST)
    165         # print(form)  #<QuerySet [<UserInfo: UserInfo object>, <UserInfo: UserInfo object>, <UserInfo: UserInfo object>]>
    166         if form.is_valid():# 开始验证
    167             cls_list = form.cleaned_data.pop("teacher_classes")
    168             print("============id",cls_list)
    169             form.cleaned_data['ut_id'] = 1
    170             #创建新老师的对象
    171             teacher_obj = models.UserInfo.objects.create(**form.cleaned_data)
    172             #创建新老师和班级的关系
    173             teacher_obj.teacher_classes.add(*cls_list)  #以前添加的是对象,现在也可以吧id添加进去
    174             return redirect("/teacherindex/")
    175         else:
    176             # print("=====?",form.errors,type(form.errors))#返回失败的结果
    177             # print(form.errors["username"][0])   #拿到返回失败的结果,渲染到页面
    178             return render(request, "addteacher.html", {"form":form})
    179 
    180 def editteacher(request,nid):
    181     obj = models.UserInfo.objects.filter(id=nid, ut_id=1).first()
    182     # print(obj.username)
    183     if not obj:
    184         return redirect("/teacherindex/")
    185     if request.method=="GET":
    186         print([obj.id for obj in obj.teacher_classes.all()])  #[2]  拿到select框的id是为了要做默认显示的
    187         form = TeacherForm(initial={"username":obj.username,"password":obj.password,"email":obj.email,"teacher_classes":[obj.id for obj in obj.teacher_classes.all()]}) #就让显示一个input框,并且带有原来哪一行的内容
    188         return render(request, "editteacher.html", {"form":form})
    189     else:
    190         form = TeacherForm(data=request.POST)
    191         if form.is_valid():#开始校验,注意这要加括号
    192             cls_list = form.cleaned_data.pop("teacher_classes")
    193             print(cls_list)
    194             models.UserInfo.objects.filter(id=nid).update(**form.cleaned_data)
    195             obj.teacher_classes.set(cls_list)   #更新第三张表
    196             return redirect("/teacherindex/")
    197         else:
    198             return render(request, "editteacher.html", {"form":form})
    199 
    200 def delteacher(request,nid):
    201     models.UserInfo.objects.filter(id=nid).delete()
    202     return redirect("/teacherindex/")
    203 
    204 
    205 
    206 def studentindex(request):
    207     username = request.session.get("username")
    208     student_obj = models.Student.objects.all()
    209     return render(request,"studentindex.html",{"student_obj":student_obj,"username":username})
    210 
    211 def addstudent(request):
    212     if request.method=="GET":
    213         form = StudentForm()
    214         return render(request,"addstudent.html",{"form":form})
    215     else:
    216         form = StudentForm(data=request.POST)
    217         if form.is_valid():
    218             print(form.cleaned_data)
    219             models.Student.objects.create(**form.cleaned_data)
    220             return redirect("/studentindex/")
    221         else:
    222             return render(request,"addstudent.html",{"form":form})
    223 
    224 def delstudent(request,nid):
    225     models.Student.objects.filter(id=nid).delete()
    226     return redirect("/studentindex/")
    227 
    228 def editstudent(request,nid):
    229     if request.method=="GET":
    230         student_obj = models.Student.objects.filter(id=nid).first()
    231         print(student_obj.cls_id)
    232         if not student_obj:
    233             return redirect("/studentindex/")
    234         form = StudentForm(initial={"name":student_obj.name,"age":student_obj.age,"cls_id":student_obj.cls_id})  #这个name是设置的字段名
    235         # form = StudentForm(initial=student_obj.values("name","age").first())  #显示input并且让带有你点击哪一行的数据
    236         return render(request,"editstudent.html",{"form":form})
    237     else:
    238         form = StudentForm(data=request.POST)
    239         if form.is_valid():
    240             models.Student.objects.filter(id=nid).update(**form.cleaned_data)
    241             return redirect("/studentindex/")
    242         else:
    243             return render(request,"editstudent.html",{"form":form})
    244 
    245 
    246 
    247 def classindex(request):
    248     class_obj = models.Classes.objects.all()
    249     username = request.session.get("username")
    250     return render(request,"classindex.html",{"class_obj":class_obj,"username":username})
    251 
    252 def delclass(request,nid):
    253     models.Classes.objects.filter(id=nid).delete()
    254     return redirect("/classindex/")
    255 
    256 def addclass(request):
    257     if request.method=="GET":
    258         form = ClassesForm()
    259         return render(request,"addclass.html",{"form":form})
    260     else:
    261         form = ClassesForm(data=request.POST)
    262         if form.is_valid():
    263             print(form.cleaned_data)
    264             models.Classes.objects.create(**form.cleaned_data)
    265             return redirect("/classindex/")
    266         else:
    267             return render(request,"addclass.html",{"form":form})
    268 
    269 def editclass(request,nid):
    270     if request.method == "GET":
    271         class_obj = models.Classes.objects.filter(id=nid).first()
    272         if not class_obj:
    273             return redirect("/classindex/")
    274         form = ClassesForm(initial={"name": class_obj.name,"classteacher_id":class_obj.classteacher_id})  # 这个name是设置的字段名,后面的那个做默认选中
    275         # form = StudentForm(initial=student_obj.values("name","age").first())  #显示input并且让带有你点击哪一行的数据
    276         return render(request, "editclass.html", {"form": form})
    277     else:
    278         form = ClassesForm(data=request.POST)
    279         if form.is_valid():
    280             models.Classes.objects.filter(id=nid).update(**form.cleaned_data)
    281             return redirect("/classindex/")
    282         else:
    283             return render(request, "editclass.html", {"form": form})
    284 
    285 
    286 def testMD(request):
    287     print("view.test")
    288     return HttpResponse("...")
    Views.py

    3、template

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     6     <meta name="viewport" content="width=device-width">
     7     <title>Title</title>
     8 </head>
     9 <body>
    10 <form method="post" novalidate>
    11     {% csrf_token %}
    12     <p>用户名:{{ form.username }}{{ form.username.errors.0 }}</p>
    13     <p>密码:{{ form.password }}{{ form.password.errors.0 }}</p>
    14     <p>{{ s }}</p>
    15     <p><input type="submit"></p>
    16 </form>
    17 </body>
    18 </html>
    login.html
     1 <!DOCTYPE html>
     2 <html lang="en">
     3 <head>
     4     <meta charset="UTF-8">
     5     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     6     <meta name="viewport" content="width=device-width">
     7     <title>Title</title>
     8     <style>
     9         .left{
    10              30%;
    11             height: 400px;
    12             position: relative;
    13         }
    14         .right{
    15              60%;
    16             height: 400px;
    17             position: absolute;
    18             left: 300px;
    19             top: 90px;
    20         }
    21         .c1{
    22             margin-top: 100px;
    23         }
    24     </style>
    25 </head>
    26 <body>
    27 <hr>
    28 <div class="c1">
    29     <div class="left">
    30         <ul>
    31             <li><a href="/teacherindex/">老师管理</a></li>
    32             <li><a href="/studentindex/">学生管理</a></li>
    33             <li><a href="/classindex/">班级管理</a></li>
    34         </ul>
    35     </div>
    36     <div class="right">
    37         {% block right %}
    38 
    39         {% endblock %}
    40     </div>
    41 </div>
    42 </body>
    43 </html>
    base.html
     1 {% extends "base.html" %}
     2 {% block right %}
     3     <h2>欢迎{{ username }}登录</h2>
     4     <h3>学生信息管理</h3>
     5     <hr>
     6     <a href="/addstudent/"><button>添加学生</button></a>
     7     <table border="1">
     8        <thead>
     9             <tr>
    10                 <th>编号</th>
    11                 <th>姓名</th>
    12                 <th>年龄</th>
    13                 <th>班级</th>
    14                 <th>操作</th>
    15             </tr>
    16        </thead>
    17         <tbody>
    18         {% for s_obj in student_obj %}
    19             <tr>
    20                     <td>{{ forloop.counter }}</td>
    21                     <td>{{ s_obj.name }}</td>
    22                     <td>{{ s_obj.age }}</td>
    23                     <td>{{ s_obj.cls.name }}</td>
    24                     <td>
    25                         <a href="/editstudent/{{ s_obj.id }}"><button>编辑</button></a>
    26                         <a href="/delstudent/{{ s_obj.id }}"><button>删除</button></a>
    27                     </td>
    28             </tr>
    29         {% endfor %}
    30         </tbody>
    31    </table>
    32 {% endblock %}
    studentindex.html
     1 {% extends "base.html" %}
     2 {% block right %}
     3     <h2>欢迎{{ username }}登录</h2>
     4     <h3>老师信息管理</h3>
     5     <hr>
     6     <a href="/addteacher/"><button>添加老师</button></a>
     7     <table border="1">
     8        <thead>
     9             <tr>
    10                 <th>编号</th>
    11                 <th>姓名</th>
    12                 <th>邮箱</th>
    13                 <th>任教班级</th>
    14                 <th>操作</th>
    15             </tr>
    16        </thead>
    17         <tbody>
    18         {% for t_obj in teacher_obj %}
    19             <tr>
    20                     <td>{{ forloop.counter }}</td>
    21                     <td>{{ t_obj.username }}</td>
    22                     <td>{{ t_obj.email }}</td>
    23 {#                    <td>{{ t_obj.teacher_classes }}</td>#}
    24 {#                    多对多查关联字段#}
    25                     <td>
    26                         {% for foo in t_obj.teacher_classes.all %}
    27                             {{ foo.name }}
    28                         {% endfor %}
    29                     </td>
    30                     <td>
    31                         <a href="/editteacher/{{ t_obj.id }}"><button>编辑</button></a>
    32                         <a href="/delteacher/{{ t_obj.id }}"><button>删除</button></a>
    33                     </td>
    34             </tr>
    35         {% endfor %}
    36         </tbody>
    37    </table>
    38 {% endblock %}
    teacherindex.html
     1 {% extends "base.html" %}
     2 {% block right %}
     3     <h2>欢迎{{ username }}登录</h2>
     4     <h3>班级信息管理</h3>
     5     <hr>
     6     <a href="/addclass/"><button>添加班级</button></a>
     7     <table border="1">
     8        <thead>
     9             <tr>
    10                 <th>编号</th>
    11                 <th>姓名</th>
    12                 <th>班主任</th>
    13                 <th>操作</th>
    14             </tr>
    15        </thead>
    16         <tbody>
    17         {% for c_obj in class_obj %}
    18             <tr>
    19                     <td>{{ forloop.counter }}</td>
    20                     <td>{{ c_obj.name }}</td>
    21                     <td>{{ c_obj.classteacher.username }}</td>
    22 {#                    <td>{{ t_obj.ut.title }}</td>#}
    23                     <td>
    24                         <a href="/editclass/{{ c_obj.id }}"><button>编辑</button></a>
    25                         <a href="/delclass/{{ c_obj.id }}"><button>删除</button></a>
    26                     </td>
    27             </tr>
    28         {% endfor %}
    29         </tbody>
    30    </table>
    31 {% endblock %}
    classindex,html
     1 {% extends "base.html" %}
     2 {% block right %}
     3 <form action="" method="post" novalidate>
     4     {% csrf_token %}
     5     <h1>添加学生信息</h1>
     6     <hr>
     7     <p>姓名:{{ form.name }}{{ form.name.errors.0 }}</p>
     8     <p>年龄:{{ form.age }}{{ form.age.errors.0 }}</p>
     9     <p>班级:{{ form.cls_id }}{{ form.cls_id.errors.0 }}</p>
    10     <input type="submit">
    11 </form>
    12 {% endblock %}
    addstudent.html
     1 {% extends "base.html" %}
     2 {% block right %}
     3     <h1>添加老师信息</h1>
     4     <hr>
     5     <form method="post" novalidate>
     6         {% csrf_token %}
     7 {#        <p>姓名:{{ form.username }}{{ form.errors.username.0 }}</p>#}
     8 {#        <p>密码:{{ form.password }}{{ form.errors.password.0 }}</p>#}
     9 {#        <p>邮箱:{{ form.email }}{{ form.errors.email.0 }}</p>#}
    10 {#        也可以循环添加#}
    11         {% for field in form %}
    12             <p>{{ field.label_tag }}{{ field }}{{ field.errors.0 }}</p>
    13         {% endfor %}
    14 
    15         <p><input type="submit" value="提交"></p>
    16     </form>
    17 {% endblock %}
    addteacher.html
     1 {% extends "base.html" %}
     2 {% block right %}
     3 <form action="" method="post" novalidate>
     4     {% csrf_token %}
     5     <h1>添加班级信息</h1>
     6     <hr>
     7     <p>班级:{{ form.name }}{{ form.age.errors.0 }}</p>
     8     <p>班主任:{{ form.classteacher_id }}{{ form.classteacher_id.errors.0 }}</p>
     9     <input type="submit">
    10 </form>
    11 {% endblock %}
    addclass.html
     1 {% extends "base.html" %}
     2 {% block right %}
     3 <form action="" method="post" novalidate>
     4     {% csrf_token %}
     5     <h1>修改学生信息</h1>
     6     <hr>
     7     <p>姓名:{{ form.name }}{{ form.name.errors.0 }}</p>
     8     <p>年龄:{{ form.age }}{{ form.age.errors.0 }}</p>
     9     <p>班级:{{ form.cls_id }}{{ form.cls_id.errors.0 }}</p>
    10     <input type="submit">
    11 </form>
    12 {% endblock %}
    editstudent
     1 {% extends "base.html" %}
     2 {% block right %}
     3     <h1>修改老师信息</h1>
     4     <hr>
     5     <form method="post" novalidate>
     6         {% csrf_token %}
     7 {#            {{ form.as_p}}#}
     8     <p>姓名:{{ form.username }}{{ form.errors.username.0 }}</p>
     9     <p>密码:{{ form.password }}{{ form.errors.password.0 }}</p>
    10     <p>邮箱:{{ form.email }}{{ form.errors.email.0 }}</p>
    11     <p>任教班级:{{ form.teacher_classes }}</p>
    12 {#    {% for field in form %}#}
    13 {#        <p>{{ field.label_tag }}{{ field }}{{ field.errors.0 }}</p>#}
    14 {#    {% endfor %}#}
    15     <input type="submit" value="提交">
    16     </form>
    17 {% endblock %}
    editteacher
     1 {% extends "base.html" %}
     2 {% block right %}
     3 <form action="" method="post" novalidate>
     4     {% csrf_token %}
     5     <h1>修改班级信息</h1>
     6     <hr>
     7     <p>班级:{{ form.name }}{{ form.age.errors.0 }}</p>
     8     <p>班主任:{{ form.classteacher_id }}{{ form.classteacher_id.errors.0 }}</p>
     9     <input type="submit">
    10 </form>
    11 {% endblock %}
    editclass

    4、中间件

     1 #!usr/bin/env python
     2 # -*- coding:utf-8 -*-
     3 # from django.utils.deprecation import MiddlewareMixin
     4 from django.conf import settings
     5 from django.shortcuts import redirect
     6 class MiddlewareMixin(object):
     7     def __init__(self, get_response=None):
     8         self.get_response = get_response
     9         super(MiddlewareMixin, self).__init__()
    10 
    11     def __call__(self, request):
    12         response = None
    13         if hasattr(self, 'process_request'):
    14             response = self.process_request(request)
    15         if not response:
    16             response = self.get_response(request)
    17         if hasattr(self, 'process_response'):
    18             response = self.process_response(request, response)
    19         return response
    20 
    21 # 至少要有两个类
    22 class Md1(MiddlewareMixin):  #必须继承
    23     def process_request(self,request):
    24         print("md1===process_request")
    25         l = ["/login/"]
    26         if request.path_info in l:  #因为login不做验证,就直接返回none就行了
    27             return None
    28         if not request.session.get(settings.GDP):
    29             return redirect("/login/")
    30         #
    31         # 如果无返回值,就继续执行后续中间件和视图函数
    32         # 如果有返回值,就执行自己的process_response和上面的response
    33     def process_response(self,request,response):
    34         print("md1====process_response1")
    35         return response   #必须有返回值
    36 
    37 class Md2(MiddlewareMixin):
    38     def process_request(self,request):
    39         print("md2====process_request2")
    40     def process_response(self,request,response):
    41         print("md2====process_response2")
    42         return response
    middlewear

    5、settings

      1 """
      2 Django settings for day75以及周末作业老师管理等 project.
      3 
      4 Generated by 'django-admin startproject' using Django 1.11.6.
      5 
      6 For more information on this file, see
      7 https://docs.djangoproject.com/en/1.11/topics/settings/
      8 
      9 For the full list of settings and their values, see
     10 https://docs.djangoproject.com/en/1.11/ref/settings/
     11 """
     12 
     13 import os
     14 
     15 # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
     16 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
     17 
     18 
     19 # Quick-start development settings - unsuitable for production
     20 # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
     21 
     22 # SECURITY WARNING: keep the secret key used in production secret!
     23 SECRET_KEY = 'xi^$lfsye5x43af&)lpkx5l%^4%3$%qmx@5=+nrbwa^!b2aj)!'
     24 
     25 # SECURITY WARNING: don't run with debug turned on in production!
     26 DEBUG = True
     27 
     28 ALLOWED_HOSTS = []
     29 
     30 
     31 # Application definition
     32 
     33 INSTALLED_APPS = [
     34     'django.contrib.admin',
     35     'django.contrib.auth',
     36     'django.contrib.contenttypes',
     37     'django.contrib.sessions',
     38     'django.contrib.messages',
     39     'django.contrib.staticfiles',
     40     'app01.apps.App01Config',
     41 ]
     42 
     43 MIDDLEWARE = [
     44     'django.middleware.security.SecurityMiddleware',
     45     'django.contrib.sessions.middleware.SessionMiddleware',
     46     'django.middleware.common.CommonMiddleware',
     47     'django.middleware.csrf.CsrfViewMiddleware',
     48     'django.contrib.auth.middleware.AuthenticationMiddleware',
     49     'django.contrib.messages.middleware.MessageMiddleware',
     50     'django.middleware.clickjacking.XFrameOptionsMiddleware',
     51     #这是自定义的中间件
     52     "middle.middle.Md1",
     53     "middle.middle.Md2"
     54 ]
     55 
     56 ROOT_URLCONF = 'day75以及周末作业老师管理等.urls'
     57 
     58 TEMPLATES = [
     59     {
     60         'BACKEND': 'django.template.backends.django.DjangoTemplates',
     61         'DIRS': [os.path.join(BASE_DIR, 'templates')]
     62         ,
     63         'APP_DIRS': True,
     64         'OPTIONS': {
     65             'context_processors': [
     66                 'django.template.context_processors.debug',
     67                 'django.template.context_processors.request',
     68                 'django.contrib.auth.context_processors.auth',
     69                 'django.contrib.messages.context_processors.messages',
     70             ],
     71         },
     72     },
     73 ]
     74 
     75 WSGI_APPLICATION = 'day75以及周末作业老师管理等.wsgi.application'
     76 
     77 
     78 # Database
     79 # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
     80 
     81 DATABASES = {
     82     'default': {
     83         'ENGINE': 'django.db.backends.sqlite3',
     84         'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
     85     }
     86 }
     87 
     88 
     89 # Password validation
     90 # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
     91 
     92 AUTH_PASSWORD_VALIDATORS = [
     93     {
     94         'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
     95     },
     96     {
     97         'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
     98     },
     99     {
    100         'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    101     },
    102     {
    103         'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    104     },
    105 ]
    106 
    107 
    108 # Internationalization
    109 # https://docs.djangoproject.com/en/1.11/topics/i18n/
    110 
    111 LANGUAGE_CODE = 'en-us'
    112 
    113 TIME_ZONE = 'UTC'
    114 
    115 USE_I18N = True
    116 
    117 USE_L10N = True
    118 
    119 USE_TZ = True
    120 
    121 
    122 # Static files (CSS, JavaScript, Images)
    123 # https://docs.djangoproject.com/en/1.11/howto/static-files/
    124 
    125 STATIC_URL = '/static/'
    126 STATICFIELDS=[
    127     os.path.join("/static/",BASE_DIR),
    128 ]
    129 
    130 # ============自定义配置文件===========
    131 ROLE_TEACHER = 1
    132 ROLE_CLASSTEACHER = 2
    133 GDP="user_info"
    settings
  • 相关阅读:
    Makefile 一点一滴(三)—— 尝试简单的变量替换
    Makefile 一点一滴(二)—— 输出文件到指定路径
    Makefile 一点一滴(一)—— 从最简单的makefile模板写起
    用fxc.exe编译shader文件(*.fx, *.hlsl)的设置
    全国管理系统
    [原]产品经理和韦小宝
    [原]详细分析 javascript 的内存分配
    [原]看看腾讯是怎么做产品设计分析的 - 腾讯QQ音乐业务产品规划
    [原]Android布局管理器
    [原]ubuntu wubi.exe 直接加载下载好的 amd64.tar.xz
  • 原文地址:https://www.cnblogs.com/morgana/p/8496437.html
Copyright © 2020-2023  润新知