• x学生管理系统(用中间件)-------基于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
    {% extends "base.html" %}
    {% block right %}
        <h2>欢迎{{ username }}登录</h2>
        <h3>班级信息管理</h3>
        <hr>
        <a href="/addclass/"><button>添加班级</button></a>
        <table border="1">
           <thead>
                <tr>
                    <th>编号</th>
                    <th>姓名</th>
                    <th>班主任</th>
                    <th>操作</th>
                </tr>
           </thead>
            <tbody>
            {% for c_obj in class_obj %}
                <tr>
                        <td>{{ forloop.counter }}</td>
                        <td>{{ c_obj.name }}</td>
                        <td>{{ c_obj.classteacher.username }}</td>
    {#                    <td>{{ t_obj.ut.title }}</td>#}
                        <td>
                            <a href="/editclass/{{ c_obj.id }}"><button>编辑</button></a>
                            <a href="/delclass/{{ c_obj.id }}"><button>删除</button></a>
                        </td>
                </tr>
            {% endfor %}
            </tbody>
       </table>
    {% endblock %}
    
    classindex,html
    classindex,html
    {% extends "base.html" %}
    {% block right %}
    <form action="" method="post" novalidate>
        {% csrf_token %}
        <h1>添加学生信息</h1>
        <hr>
        <p>姓名:{{ form.name }}{{ form.name.errors.0 }}</p>
        <p>年龄:{{ form.age }}{{ form.age.errors.0 }}</p>
        <p>班级:{{ form.cls_id }}{{ form.cls_id.errors.0 }}</p>
        <input type="submit">
    </form>
    {% endblock %}
    
    addstudent.html
    addstudent.html
    {% extends "base.html" %}
    {% block right %}
        <h1>添加老师信息</h1>
        <hr>
        <form method="post" novalidate>
            {% csrf_token %}
    {#        <p>姓名:{{ form.username }}{{ form.errors.username.0 }}</p>#}
    {#        <p>密码:{{ form.password }}{{ form.errors.password.0 }}</p>#}
    {#        <p>邮箱:{{ form.email }}{{ form.errors.email.0 }}</p>#}
    {#        也可以循环添加#}
            {% for field in form %}
                <p>{{ field.label_tag }}{{ field }}{{ field.errors.0 }}</p>
            {% endfor %}
    
            <p><input type="submit" value="提交"></p>
        </form>
    {% endblock %}
    
    addteacher.html
    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
    {% extends "base.html" %}
    {% block right %}
    <form action="" method="post" novalidate>
        {% csrf_token %}
        <h1>修改学生信息</h1>
        <hr>
        <p>姓名:{{ form.name }}{{ form.name.errors.0 }}</p>
        <p>年龄:{{ form.age }}{{ form.age.errors.0 }}</p>
        <p>班级:{{ form.cls_id }}{{ form.cls_id.errors.0 }}</p>
        <input type="submit">
    </form>
    {% endblock %}
    
    editstudent
    editstudent
    {% extends "base.html" %}
    {% block right %}
        <h1>修改老师信息</h1>
        <hr>
        <form method="post" novalidate>
            {% csrf_token %}
    {#            {{ form.as_p}}#}
        <p>姓名:{{ form.username }}{{ form.errors.username.0 }}</p>
        <p>密码:{{ form.password }}{{ form.errors.password.0 }}</p>
        <p>邮箱:{{ form.email }}{{ form.errors.email.0 }}</p>
        <p>任教班级:{{ form.teacher_classes }}</p>
    {#    {% for field in form %}#}
    {#        <p>{{ field.label_tag }}{{ field }}{{ field.errors.0 }}</p>#}
    {#    {% endfor %}#}
        <input type="submit" value="提交">
        </form>
    {% endblock %}
    
    editteacher
    editteacher
    {% extends "base.html" %}
    {% block right %}
    <form action="" method="post" novalidate>
        {% csrf_token %}
        <h1>修改班级信息</h1>
        <hr>
        <p>班级:{{ form.name }}{{ form.age.errors.0 }}</p>
        <p>班主任:{{ form.classteacher_id }}{{ form.classteacher_id.errors.0 }}</p>
        <input type="submit">
    </form>
    {% endblock %}
    
    editclass
    editclass

    4、中间件

    #!usr/bin/env python
    # -*- coding:utf-8 -*-
    # from django.utils.deprecation import MiddlewareMixin
    from django.conf import settings
    from django.shortcuts import redirect
    class MiddlewareMixin(object):
        def __init__(self, get_response=None):
            self.get_response = get_response
            super(MiddlewareMixin, self).__init__()
    
        def __call__(self, request):
            response = None
            if hasattr(self, 'process_request'):
                response = self.process_request(request)
            if not response:
                response = self.get_response(request)
            if hasattr(self, 'process_response'):
                response = self.process_response(request, response)
            return response
    
    # 至少要有两个类
    class Md1(MiddlewareMixin):  #必须继承
        def process_request(self,request):
            print("md1===process_request")
            l = ["/login/"]
            if request.path_info in l:  #因为login不做验证,就直接返回none就行了
                return None
            if not request.session.get(settings.GDP):
                return redirect("/login/")
            #
            # 如果无返回值,就继续执行后续中间件和视图函数
            # 如果有返回值,就执行自己的process_response和上面的response
        def process_response(self,request,response):
            print("md1====process_response1")
            return response   #必须有返回值
    
    class Md2(MiddlewareMixin):
        def process_request(self,request):
            print("md2====process_request2")
        def process_response(self,request,response):
            print("md2====process_response2")
            return response
    
    middlewear
    middlewear

    5、settings

    """
    Django settings for 管理 project.
    
    Generated by 'django-admin startproject' using Django 1.11.6.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/1.11/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.11/ref/settings/
    """
    
    import os
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = 'xi^$lfsye5x43af&)lpkx5l%^4%3$%qmx@5=+nrbwa^!b2aj)!'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'app01.apps.App01Config',
    ]
    
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        #这是自定义的中间件
        "middle.middle.Md1",
        "middle.middle.Md2"
    ]
    
    ROOT_URLCONF = '管理.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [os.path.join(BASE_DIR, 'templates')]
            ,
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'day75以及周末作业老师管理等.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/1.11/ref/settings/#databases
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        }
    }
    
    
    # Password validation
    # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/1.11/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = True
    
    USE_L10N = True
    
    USE_TZ = True
    
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.11/howto/static-files/
    
    STATIC_URL = '/static/'
    STATICFIELDS=[
        os.path.join("/static/",BASE_DIR),
    ]
    
    # ============自定义配置文件===========
    ROLE_TEACHER = 1
    ROLE_CLASSTEACHER = 2
    GDP="user_info"
    
    settings
    
    settings
    View Code
  • 相关阅读:
    mini2440 UBoot启动过程完全分析
    Linux Shell常用命令学习(1)
    S3C6410启动模式介绍
    漫画与新媒体的传播思考
    注册表修改启动项
    邮件主题是乱码的原因gbk 在utf8 显示问题
    移动 电话费 套餐
    java 异常的问题讨论
    领结的打法
    c# 字符之间的转换
  • 原文地址:https://www.cnblogs.com/mqhpy/p/11373626.html
Copyright © 2020-2023  润新知