Django学生管理系统

  1. urlpatterns = [
  2. url(r'^admin/', admin.site.urls),
  3.  
  4. url(r'^class_list/', views.class_list),
  5. url(r'^add_class/', views.add_class),
  6. url(r'^edit_class/(\d+)/', views.edit_class),
  7.  
  8. url(r'^student_list/', views.student_list),
  9. url(r'^add_student/', views.add_student),
  10. url(r'^edit_student/(\d+)/', views.edit_student),
  11.  
  12. url(r'^teacher_list/', views.teacher_list),
  13. url(r'^add_teacher/', views.add_teacher),
  14. url(r'^edit_teacher/(\d+)/', views.edit_teacher),
  15.  
  16. ]

urls.py

  1. from django.shortcuts import render,redirect,HttpResponse
  2. from app01 import models
  3. from django.forms import Form
  4. from django.forms import fields
  5. from django.forms import widgets
  6. from django.forms import models as form_model
  7. from django.core.exceptions import ValidationError
  8. from django.core.validators import RegexValidator
  9.  
  10. class ClassForm(Form):
  11. title = fields.RegexField('全栈\d+')
  12.  
  13. def class_list(request):
  14. cls_list = models.Classes.objects.all()
  15. return render(request,'class_list.html',{'cls_list':cls_list})
  16.  
  17. def add_class(request):
  18. if request.method == "GET":
  19. obj = ClassForm()
  20. return render(request,'add_class.html',{'obj': obj})
  21. else:
  22. obj = ClassForm(request.POST)
  23. if obj.is_valid():
  24. # obj.cleaned_data # 字典
  25. # 数据库创建一条数据
  26. # print(obj.cleaned_data)
  27. # models.Classes.objects.create(title=obj.cleaned_data['tt'])
  28.  
  29. models.Classes.objects.create(**obj.cleaned_data)
  30. return redirect('/class_list/')
  31. return render(request,'add_class.html',{'obj': obj})
  32.  
  33. def edit_class(request,nid):
  34. if request.method == "GET":
  35. row = models.Classes.objects.filter(id=nid).first()
  36. # 让页面显示初始值
  37. # obj = ClassForm(data={'title': 'asdfasdfasdfas'})
  38. obj = ClassForm(initial={'title': row.title})
  39. return render(request,'edit_class.html',{'nid': nid,'obj':obj})
  40. else:
  41. obj = ClassForm(request.POST)
  42. if obj.is_valid():
  43. print(obj.cleaned_data)
  44. models.Classes.objects.filter(id=nid).update(**obj.cleaned_data)
  45. return redirect('/class_list/')
  46. return render(request,'edit_class.html',{'nid': nid,'obj':obj})
  47.  
  48. class StudentForm(Form):
  49. name = fields.CharField(
  50. min_length=2,
  51. max_length=6,
  52. widget=widgets.TextInput(attrs={'class': 'form-control'})
  53. )
  54. email = fields.EmailField(widget=widgets.TextInput(attrs={'class': 'form-control'}))
  55. age = fields.IntegerField(min_value=18,max_value=25,widget=widgets.TextInput(attrs={'class': 'form-control'}))
  56. cls_id = fields.IntegerField(
  57. # widget=widgets.Select(choices=[(1,'上海'),(2,'北京')])
  58. widget=widgets.Select(choices=models.Classes.objects.values_list('id','title'),attrs={'class': 'form-control'})
  59. )
  60.  
  61. def student_list(request):
  62.  
  63. stu_list = models.Student.objects.all()
  64. return render(request,'student_list.html',{'stu_list':stu_list})
  65.  
  66. def add_student(request):
  67. if request.method == "GET":
  68. obj = StudentForm()
  69. return render(request,'add_student.html',{'obj':obj})
  70. else:
  71. obj = StudentForm(request.POST)
  72. if obj.is_valid():
  73. models.Student.objects.create(**obj.cleaned_data)
  74. return redirect('/student_list/')
  75. return render(request,'add_student.html',{'obj':obj})
  76.  
  77. def edit_student(request,nid):
  78. if request.method == "GET":
  79. row = models.Student.objects.filter(id=nid).values('name','email','age','cls_id').first()
  80. obj = StudentForm(initial=row)
  81. return render(request,'edit_student.html',{'nid':nid,'obj': obj})
  82. else:
  83. obj = StudentForm(request.POST)
  84. if obj.is_valid():
  85. models.Student.objects.filter(id=nid).update(**obj.cleaned_data)
  86. return redirect('/student_list/')
  87. return render(request,'edit_student.html',{'nid':nid,'obj': obj})
  88.  
  89. class TeacherForm(Form):
  90. tname = fields.CharField(min_length=2)
  91. xx = fields.MultipleChoiceField(
  92. # choices=models.Classes.objects.values_list("id","title"),
  93. widget=widgets.SelectMultiple
  94. )
  95. def __init__(self,*args,**kwargs):
  96. super(TeacherForm,self).__init__(*args,**kwargs)
  97. self.fields["xx"].choices =models.Classes.objects.values_list("id","title")
  98.  
  99. def teacher_list(request):
  100. tea_list = models.Teacher.objects.all()
  101. # tea_class = tea_list.c2t.all()
  102. # print(tea_class)
  103. return render(request,"teacher_list.html",{"tea_list":tea_list})
  104.  
  105. def add_teacher(request):
  106. if request.method == "GET":
  107. obj = TeacherForm()
  108. # # print(obj.xx)
  109. # print(obj.tname)
  110. return render(request,"add_teacher.html",{"obj":obj})
  111. else:
  112. obj = TeacherForm(request.POST)
  113. if obj.is_valid():
  114. print(obj.cleaned_data)
  115. xx = obj.cleaned_data.pop("xx")
  116. row = models.Teacher.objects.create(**obj.cleaned_data)
  117. row.c2t.add(*xx)
  118. return redirect("/teacher_list/")
  119. return render(request,"add_teacher.html",{"obj":obj})
  120.  
  121. def edit_teacher(request,tid):
  122. if request.method == "GET":
  123. row = models.Teacher.objects.filter(id=tid).first()
  124. class_ids = row.c2t.values_list("id")
  125. print(class_ids)
  126. print(list(zip(*class_ids)))
  127. id_list = list(zip(*class_ids))[0] if list(zip(*class_ids)) else []
  128.  
  129. obj = TeacherForm(initial={'tname':row.tname,'xx':id_list})
  130. return render(request,'edit_teacher.html',{'obj':obj,"tid":tid})
  131. else:
  132.  
  133. obj = TeacherForm(request.POST)
  134. if obj.is_valid():
  135. print(obj.cleaned_data)
  136.  
  137. xx = obj.cleaned_data.pop("xx")
  138. row = models.Teacher.objects.create(**obj.cleaned_data)
  139. row.c2t.add(*xx)
  140. return redirect("/teacher_list/")
  141. else:
  142. print("")
  143. return render(request, 'edit_teacher.html', {'obj': obj, "tid": tid})

View.py

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <h1>班级列表</h1>
  9. <div>
  10. <a href="/add_class/">添加</a>
  11. </div>
  12. <ul>
  13. {% for row in cls_list %}
  14. <li>{{ row.title }} <a href="/edit_class/{{ row.id }}/">编辑</a> </li>
  15. {% endfor %}
  16. </ul>
  17. </body>
  18. </html>

class_list.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <h1>添加班级</h1>
  9. <form method="POST" action="/add_class/" novalidate>
  10. {% csrf_token %}
  11. {{ obj.title }} {{ obj.errors.title.0 }}
  12. <input type="submit" value="提交" />
  13. </form>
  14. </body>
  15. </html>

add_class.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <h1>编辑班级</h1>
  9. <form method="POST" action="/edit_class/{{ nid }}/">
  10. {% csrf_token %}
  11. <p>
  12. {{ obj.title }} {{ obj.errors.title.0 }}
  13. </p>
  14. <input type='submit' value="提交" />
  15. </form>
  16. </body>
  17. </html>

edit_class.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <h1>学生列表</h1>
  9. <a href="/add_student/">添加</a>
  10. <ul>
  11. {% for row in stu_list %}
  12. <li>{{ row.name }}-{{ row.email }}-{{ row.age }}-{{ row.cls_id }}-{{ row.cls.title }} <a href="/edit_student/{{ row.id }}/">编辑</a></li>
  13. {% endfor %}
  14. </ul>
  15. </body>
  16. </html>

student_list.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. </head>
  7. <body>
  8. <h1>添加学生</h1>
  9. <form action="/add_student/" method="POST">
  10. {% csrf_token %}
  11. <p>
  12. 学生名称:{{ obj.name }}
  13. </p>
  14. <p>
  15. 学生邮箱:{{ obj.email }}
  16. </p>
  17. <p>
  18. 学生年龄:{{ obj.age }}
  19. </p>
  20. <p>
  21. 班级:{{ obj.cls_id }}
  22. </p>
  23. <input type="submit" value="提交" />
  24. </form>
  25. </body>
  26. </html>

add_student.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title></title>
  6. <link rel="stylesheet" href="/static/bootstrap-3.3.7-dist/css/bootstrap.css"/>
  7. </head>
  8. <body>
  9.  
  10. <div style="width: 500px;margin: 0 auto;">
  11. <form class="form-horizontal" method="POST" action="/edit_student/{{ nid }}/">
  12. {% csrf_token %}
  13. <div class="form-group">
  14. <label class="col-sm-2 control-label">姓名:</label>
  15.  
  16. <div class="col-sm-10">
  17. {{ obj.name }}
  18. </div>
  19. </div>
  20. <div class="form-group">
  21. <label class="col-sm-2 control-label">邮箱:</label>
  22.  
  23. <div class="col-sm-10">
  24. {{ obj.email }}
  25. </div>
  26. </div>
  27. <div class="form-group">
  28. <label class="col-sm-2 control-label">年龄:</label>
  29.  
  30. <div class="col-sm-10">
  31. {{ obj.age }}
  32. </div>
  33. </div>
  34. <div class="form-group">
  35. <label class="col-sm-2 control-label">班级:</label>
  36.  
  37. <div class="col-sm-10">
  38. {{ obj.cls_id }}
  39. </div>
  40. </div>
  41. <div class="form-group">
  42. <div class="col-sm-offset-2 col-sm-10">
  43. <input type="submit" class="btn btn-default" value="提交" />
  44. </div>
  45. </div>
  46. </form>
  47. </div>
  48. </body>
  49. </html>

edit_student.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <h1>老师列表</h1>
  9. <div>
  10. <a href="/add_teacher/">增加</a>
  11. </div>
  12. <table border="">
  13. <thead>
  14. <tr>
  15. <th>ID</th>
  16. <th>老师名称</th>
  17. <th>任教老师</th>
  18. <th>操作</th>
  19. </tr>
  20. </thead>
  21. <tbody>
  22. {% for row in tea_list %}
  23. <tr>
  24. <td>{{ row.id }}</td>
  25. <td>{{ row.tname }}</td>
  26. <td>
  27. {% for row in row.c2t.all %}
  28. {{ row.title }}
  29. {% endfor %}
  30.  
  31. </td>
  32. <td>
  33. <a href="/edit_teacher/{{ row.id }}">编辑</a>
  34. </td>
  35. </tr>
  36. {% endfor %}
  37. </tbody>
  38. </table>
  39. </body>
  40. </html>

teacher.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <form action="/add_teacher/" method="POST">
  10. {% csrf_token %}
  11. <p>
  12. 姓名: {{ obj.tname }}
  13. </p>
  14. <p>
  15. 班级 {{ obj.xx }}
  16. </p>
  17. <input type="submit" value="提交">
  18. </form>
  19.  
  20. </body>
  21. </html>

add_teacher.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <h3>编辑老师</h3>
  9.  
  10. <form action="/edit_teacher/{{ tid }}/" novalidate method="POST">
  11. {% csrf_token %}
  12. <p>
  13. {{ obj.tname }}
  14. </p>
  15. <p>
  16. {{ obj.xx }}
  17. </p>
  18. <input type="submit" value="提交">
  19. </form>
  20. </body>
  21. </html>

edit_teacheer.html

Django学生管理系统(使用AJAX实现模态对话框)

1. 一对一 班级  模态增加 编辑

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7.  
  8. .hide{
  9. display: none;
  10. }
  11. .shadow{
  12. position: fixed;
  13. left: 0;
  14. top: 0;
  15. right: 0;
  16. bottom: 0;
  17. background-color: black;
  18. opacity: 0.4;
  19. z-index: 999;
  20. }
  21. .modal{
  22. z-index: 1000;
  23. position: fixed;
  24. left: 50%;
  25. top: 50%;
  26. height: 300px;
  27. width: 400px;
  28. background-color: white;
  29. margin-left: -200px;
  30. margin-top: -150px;
  31. }
  32.  
  33. .del_class{
  34. z-index: 1001;
  35. position: fixed;
  36. left: 50%;
  37. top: 50%;
  38. height: 150px;
  39. width: 300px;
  40. background-color: white;
  41. margin-left: -150px;
  42. margin-top: -75px;
  43. }
  44.  
  45. .edit_class{
  46. z-index: 1002;
  47. position: fixed;
  48. left: 50%;
  49. top: 50%;
  50. height: 150px;
  51. width: 300px;
  52. background-color: white;
  53. margin-left: -150px;
  54. margin-top: -75px;
  55. }
  56. </style>
  57. </head>
  58. <body>
  59.  
  60. <h1>班级列表</h1>
  61.  
  62. <div>
  63. <a onclick="showModal();">模态框增加</a>
  64. </div>
  65.  
  66. <table border="1px">
  67. <thead>
  68. <tr>
  69. <td>ID</td>
  70. <td>班级名称</td>
  71.  
  72. <td>模态操作</td>
  73. </tr>
  74. </thead>
  75. <tbody>
  76. {% for row in data %}
  77. <tr>
  78. <td>{{ row.cid }}</td>
  79. <td>{{ row.title }}</td>
  80.  
  81. <td>
  82. <a onclick="modelEdit(this)">编辑</a>
  83. <a onclick="DelClass({{ row.cid }})">删除</a>
  84. </td>
  85. </tr>
  86. {% endfor %}
  87. </tbody>
  88. </table>
  89.  
  90. {# 遮罩#}
  91. <div id="shadow" class="shadow hide"></div>
  92.  
  93. {# 增加#}
  94. <div id="addmodal" class="modal hide">
  95. <p>班级名称:
  96. <input id="addtitle" type="text" name="title" />
  97. </p>
  98. <input type="button" value="提交" onclick="AjaxSend();" /><span id="errormsg"></span>
  99. <input type="button" value="取消" onclick="cancleModal();" />
  100. </div>
  101.  
  102. {# 编辑#}
  103. <div id="editModal" class="modal hide">
  104. <h3>编辑</h3>
  105. <input id="editId" type="text" name="id" style="display: none">
  106. <p>班级名称<input id="editTitle" type="text" name="title" ></p>
  107. <input type="button" value="提交" onclick="editAjaxSend()"><span id="errormsg"></span>
  108. <input type="button" value="取消" onclick="cancleModal()">
  109. </div>
  110.  
  111. <script src="/static/jquery-3.2.1.js"></script>
  112.  
  113. <script>
  114.  
  115. {# 增加#}
  116. function showModal() {
  117. $("#addmodal,#shadow").removeClass("hide");
  118. }
  119.  
  120. function AjaxSend() {
  121. title=$("#addtitle").val();
  122. $.ajax({
  123. url: '/motai_add_class/',
  124. type: 'POST',
  125. data: {'title': title},
  126. success: function(arg){
  127. arg = JSON.parse(arg);
  128. if(arg.status){
  129. location.reload();
  130. }else{
  131. alert(arg.message);
  132. }
  133. }
  134. })
  135. }
  136.  
  137. {# 编辑#}
  138. function modelEdit(self) {
  139. $("#editModal,#shadow").removeClass("hide");
  140.  
  141. var title=$(self).parent().prevAll().eq(0).text();
  142. var id=$(self).parent().prevAll().eq(1).text();
  143. $("#editTitle").val(title);
  144. $("#editId").val(id);
  145. }
  146.  
  147. function editAjaxSend() {
  148. id = $("#editId").val();
  149. title = $("#editTitle").val();
  150. $.ajax({
  151. url: '/modal_edit_class/',
  152. type: 'POST',
  153. data: {"id":id,"title": title},
  154. success: function(arg){
  155. arg = JSON.parse(arg);
  156. if(arg.status){
  157. location.reload();
  158. }else{
  159. alert(arg.message);
  160. }
  161. }
  162. })
  163. }
  164.  
  165. {# 隐藏#}
  166. function cancleModal() {
  167. $("#shadow").addClass("hide");
  168. $("#addmodal").addClass("hide");
  169. $("#editModal").addClass("hide")
  170. }
  171.  
  172. </script>
  173.  
  174. </body>
  175. </html>

classes.html

  1. def classes(request):
  2. data = sqlheper.get_list("select cid,title from class",[])
  3. return render(request, "classes.html", {"data": data})
  4.  
  5. def motai_add_class(request):
  6. ret = {'status': True, 'message': None}
  7. title = request.POST.get('title')
  8. try:
  9. nid = request.POST.get('nid')
  10. content = request.POST.get('content')
  11. sqlheper.motify_sql('insert into class(title) values(%s)',[title,])
  12. except Exception as e:
  13. ret['status'] = False
  14. ret['message'] = "处理异常"
  15.  
  16. return HttpResponse(json.dumps(ret))
  17.  
  18. def modal_edit_class(request):
  19. print(request.POST)
  20. ret = {'status': True, 'message':None}
  21. try:
  22. id = request.POST.get('id')
  23. title = request.POST.get('title')
  24. sqlheper.motify_sql('update class set title=%s where cid=%s',[title,id,])
  25. except Exception as e:
  26. ret['status'] = False
  27. ret['message'] = "处理异常"
  28.  
  29. return HttpResponse(json.dumps(ret))

views.py

2.一对多 学生班级  模态增加 编辑

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. .hide{
  8. display: none;
  9. }
  10. .shadow{
  11. position: fixed;
  12. top: 0;
  13. bottom: 0;
  14. left: 0;
  15. right: 0;
  16. background-color: black;
  17. z-index: 999;
  18. opacity: 0.4;
  19. }
  20. .Modal{
  21. position: fixed;
  22. top: 50%;
  23. left: 50%;
  24. width: 400px;
  25. height: 300px;
  26. margin-left: -200px;
  27. margin-top: -150px;
  28. z-index: 1000;
  29. background-color: white;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34.  
  35. <h1>班级学员</h1>
  36.  
  37. <div>
  38. <a id="addStudent">模态框增加</a>
  39. </div>
  40.  
  41. <table border="1px">
  42. <thead>
  43. <tr>
  44. <td>学员名称</td>
  45. <td>学生名称</td>
  46. <td>班级名称</td>
  47. <td>模态操作</td>
  48. </tr>
  49. </thead>
  50. <tbody>
  51. {% for row in student_list %}
  52. <tr>
  53. <td>{{ row.sid }}</td>
  54. <td>{{ row.name }}</td>
  55. <td clsId="{{ row.class_id }}">{{ row.title }}</td>
  56. <td>
  57. <a class="btn-edit">编辑</a>
  58. <a >删除</a>
  59. </td>
  60. </tr>
  61. {% endfor %}
  62. </tbody>
  63. </table>
  64.  
  65. <div id="shadow" class="shadow hide"></div>
  66.  
  67. {#增加#}
  68. <div id="addModal" class="Modal hide">
  69.  
  70. <p>学生名称:
  71. <input id="add_name" type="text" name="add_name">
  72. </p>
  73. <p>学生性别:
  74. <input id="add_sex" type="text" name="add_sex">
  75. </p>
  76. <p>班级名称:
  77. <select id="add_classId" name="add_classId">
  78. {% for row in class_list %}
  79. <option value="{{ row.cid }}">{{ row.title }}</option>
  80. {% endfor %}
  81. </select>
  82. </p>
  83.  
  84. <input id="btnAdd" type="button" value="提交"><span id="addError"></span>
  85. <input id="btnCancle" type="button" value="取消">
  86.  
  87. </div>
  88.  
  89. {#编辑#}
  90. <div id="editModal" class="Modal hide">
  91. <h3>编辑学生信息</h3>
  92. <p>
  93. 姓名:<input id="editName" type="text" name="name" placeholder="姓名" />
  94. <input type="text" id="editId" style="display: none" />
  95. </p>
  96. <p>
  97. 班级:
  98. <select id="editClassId" name="classId">
  99. {% for row in class_list %}
  100. <option value="{{ row.cid }}">{{ row.title }}</option>
  101. {% endfor %}
  102. </select>
  103. </p>
  104. <input id="btnEdit" type="button" value="更新" />
  105. <span id="editError" style="color: red;"></span>
  106. <input id="btnCancle" type="button" value="取消" />
  107. </div>
  108.  
  109. <script src="/static/jquery-3.2.1.js"></script>
  110.  
  111. <script>
  112.  
  113. $(function () {
  114.  
  115. {# 增加#}
  116.  
  117. $("#addStudent").click(function () {
  118. $("#shadow,#addModal").removeClass("hide");
  119. });
  120.  
  121. $("#btnCancle").click(function () {
  122. $("#shadow,#addModal").addClass("hide");
  123. $("#editModal").addClass("hide");
  124. });
  125.  
  126. $("#btnAdd").click(function () {
  127. var add_name=$("#add_name").val();
  128. var add_age=$("#add_sex").val();
  129. var add_classId=$("#add_classId").val();
  130. $.ajax({
  131. url:"/motai_add_student/",
  132. type:"POST",
  133. data:{"add_name":add_name,"add_age":add_age,"add_classId":add_classId},
  134. success:function (arg) {
  135. arg = JSON.parse(arg);
  136. if (arg.status){
  137. location.reload();
  138. }else {
  139. $("#addError").text(arg.message);
  140. }
  141. }
  142. })
  143.  
  144. });
  145.  
  146. {# 编辑 #}
  147. $('.btn-edit').click(function(){
  148. $('#shadow,#editModal').removeClass('hide');
  149.  
  150. var tds = $(this).parent().prevAll();
  151. var studentId = $(tds[2]).text();
  152. var studentName = $(tds[1]).text();
  153. var classId = $(tds[0]).attr('clsid');
  154.  
  155. console.log(studentId,studentName,classId);
  156.  
  157. $('#editId').val(studentId);
  158. $('#editName').val(studentName);
  159. $('#editClassId').val(classId);
  160. });
  161.  
  162. $('#btnEdit').click(function(){
  163. $.ajax({
  164. url:'/motai_edit_student/',
  165. type: 'POST',
  166. data: {'sid': $('#editId').val(), 'name':$('#editName').val(),'class_id': $('#editClassId').val()},
  167. dataType: 'JSON', //JSON.parse(arg)
  168. success:function(arg){
  169. if(arg.status){
  170. location.reload();
  171. }else{
  172. $('#editError').text(arg.message);
  173. }
  174. }
  175. })
  176. });
  177. })
  178.  
  179. </script>
  180.  
  181. </body>
  182. </html>

student.html

  1. def student(request):
  2. student_list = sqlheper.get_list("select student.sid,student.name,student.class_id,class.title from student left join class on student.class_id=class.cid",[])
  3.  
  4. class_list = sqlheper.get_list("select cid,title from class",[])
  5.  
  6. return render(request, "student.html", {"student_list":student_list, "class_list":class_list})
  7.  
  8. def motai_add_student(request):
  9. print(request.POST)
  10. ret = {"status":True,"message":None}
  11. try:
  12. name = request.POST.get("add_name")
  13. age = request.POST.get("add_age")
  14. classId = request.POST.get("add_classId")
  15.  
  16. sqlheper.motify_sql("insert into student(name,age,class_id) values(%s,%s,%s)",[name,age,classId,])
  17. except Exception as e:
  18. ret["status"] = False
  19. ret["message"] = str(e)
  20. return HttpResponse(json.dumps(ret))
  21.  
  22. def motai_edit_student(request):
  23. ret = {'status': True,'message': None}
  24. try:
  25.  
  26. print(request.POST)
  27. sid = request.POST.get('sid')
  28. name = request.POST.get('name')
  29. class_id = request.POST.get('class_id')
  30. sqlheper.motify_sql('update student set name=%s,class_id=%s where sid=%s',[name,class_id,sid,])
  31. except Exception as e:
  32. ret['status'] = False
  33. ret['message'] = str(e)
  34. return HttpResponse(json.dumps(ret))

views.py

3.多对多 老师 班级  模态增加 编辑

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. .hide{
  8. display: none;
  9. }
  10. .shadow{
  11. position: fixed;
  12. top: 0;
  13. bottom: 0;
  14. left: 0;
  15. right: 0;
  16. background-color: black;
  17. z-index: 999;
  18. opacity: 0.4;
  19. }
  20. .Modal{
  21. position: fixed;
  22. top: 50%;
  23. left: 50%;
  24. width: 400px;
  25. height: 300px;
  26. margin-left: -200px;
  27. margin-top: -150px;
  28. z-index: 1000;
  29. background-color: white;
  30. }
  31. </style>
  32. </head>
  33. <body>
  34.  
  35. <h1>老师 班级管理</h1>
  36.  
  37. <div>
  38.  
  39. <a id="addModal">模态框增加</a>
  40. </div>
  41.  
  42. <table border="solid" >
  43. <thead>
  44. <tr>
  45. <td>ID</td>
  46. <td>老师名称</td>
  47. <td>班级名称</td>
  48. <td>操作</td>
  49. </tr>
  50. </thead>
  51. <tbody>
  52. {% for row in teacher_list %}
  53. <tr>
  54. <td>{{ row.tid }}</td>
  55. <td>{{ row.name }}</td>
  56. <td>
  57. {% for item in row.titles %}
  58. {{ item }}
  59. {% endfor %}
  60. </td>
  61. <td>
  62. <a class="editModal">编辑</a>
  63. <a class="delModal">删除</a>
  64. </td>
  65. </tr>
  66. {% endfor %}
  67. </tbody>
  68.  
  69. </table>
  70.  
  71. <div id="shadow" class="shadow hide"></div>
  72.  
  73. <div id="add_tea_cls" class="Modal hide">
  74.  
  75. <p>老师名称:
  76. <input id="add_name" type="text" name="add_name">
  77. </p>
  78.  
  79. <p>班级名称:
  80. <select id="add_classId" name="add_classId" multiple>
  81. {% for row in class_list %}
  82. <option value="{{ row.cid }}">{{ row.title }}</option>
  83. {% endfor %}
  84. </select>
  85. </p>
  86. <input id="btnAdd" type="button" value="提交"><span id="addError"></span>
  87. <input id="btnCancle" type="button" value="取消">
  88.  
  89. </div>
  90.  
  91. <div id="edit_tea_cls" class="Modal hide">
  92.  
  93. <p>老师名称:
  94. <input id="add_name" type="text" name="add_name">
  95. </p>
  96.  
  97. <p>班级名称:
  98. <select id="add_classId" name="add_classId" multiple>
  99. {% for row in class_list %}
  100. <option value="{{ row.cid }}">{{ row.title }}</option>
  101. {% endfor %}
  102. </select>
  103. </p>
  104. <input id="btnEdit" type="button" value="提交"><span id="addError"></span>
  105. <input id="cacleEdit" type="button" value="取消">
  106.  
  107. </div>
  108.  
  109. <script src="/static/jquery-3.2.1.js"></script>
  110.  
  111. <script>
  112.  
  113. $(function () {
  114.  
  115. {# 增加#}
  116. $("#addModal").click(function () {
  117. $("#shadow,#add_tea_cls").removeClass("hide");
  118. });
  119.  
  120. $("#btnCancle").click(function () {
  121. $("#shadow,#add_tea_cls").addClass("hide");
  122. });
  123.  
  124. $("#btnAdd").click(function () {
  125. tname=$("#add_name").val();
  126. class_list=$("#add_classId").val();
  127. console.log(class_list)
  128. $.ajax({
  129. url:"/new_teacher/",
  130. type:"POST",
  131. data:{"tname":tname,"class_list":class_list},
  132. success:function (arg) {
  133. arg = JSON.parse(arg);
  134. if (arg.status){
  135. location.reload();
  136. }else {
  137. $("#addError").text(arg.message);
  138. }
  139. }
  140. })
  141. });
  142.  
  143. {# 编辑#}
  144. $(".editModal").click(function () {
  145. $("#shadow").removeClass("hide");
  146. $("#edit_tea_cls").removeClass("hide");
  147. });
  148.  
  149. $("#cacleEdit").click(function () {
  150. $("#shadow,#edit_tea_cls").addClass("hide");
  151. });
  152.  
  153. })
  154.  
  155. </script>
  156.  
  157. </body>
  158. </html>

teacher.html

  1. def teacher(request):
  2.  
  3. teacher_list=sqlheper.get_list("""
  4. select teacher.tid as tid,teacher.name,class.title from teacher
  5. left join teacher_class on teacher_class.teacher_id=teacher.tid
  6. left join class on class.cid=teacher_class.class_id""",[])
  7. # print(teacher_list)
  8. result = {}
  9. for row in teacher_list:
  10. tid = row["tid"]
  11. if tid in result:
  12. result[tid]["titles"].append(row["title"])
  13. else:
  14. result[tid] = {"tid":row["tid"],"name":row["name"],"titles":[row["title"],]}
  15.  
  16. class_list = sqlheper.get_list("select cid,title from class",[])
  17.  
  18. return render(request, "teacher.html_模态增加 老师班级", {"teacher_list":result.values(), "class_list":class_list})
  19.  
  20. ###模态增加
  21. def new_teacher(request):
  22. print(request.POST)
  23. ret = {'status': True, 'message': None}
  24. try:
  25. class_list=request.POST.getlist("class_list[]")
  26. tname=request.POST.get("tname")
  27. print(class_list)
  28. print(tname)
  29. teacher_id=sqlheper.get_IncrementId("insert into teacher(name) values(%s)",[tname,])
  30. for item in class_list:
  31. sqlheper.motify_sql("insert into teacher_class(teacher_id,class_id) values(%s,%s)",[teacher_id,item,])
  32. except Exception as e:
  33. ret['status'] = False
  34. ret['message'] = str(e)
  35. return HttpResponse(json.dumps(ret))

views.py

4.多对多 老师 班级  新url  增加 编辑

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6.  
  7. </head>
  8. <body>
  9.  
  10. <h1>老师 班级管理</h1>
  11.  
  12. <div>
  13.  
  14. <a href="/add_page_teacher/">增加</a>
  15. </div>
  16.  
  17. <table border="solid" >
  18. <thead>
  19. <tr>
  20. <td>ID</td>
  21. <td>老师名称</td>
  22. <td>班级名称</td>
  23. <td>操作</td>
  24. </tr>
  25. </thead>
  26. <tbody>
  27. {% for row in teacher_list %}
  28. <tr>
  29. <td>{{ row.tid }}</td>
  30. <td>{{ row.name }}</td>
  31. <td>
  32. {% for item in row.titles %}
  33. {{ item }}
  34. {% endfor %}
  35. </td>
  36. <td>
  37. <a href="/edit_page_teacher/?tid={{ row.tid }}">编辑</a>
  38. <a >删除</a>
  39. </td>
  40. </tr>
  41. {% endfor %}
  42. </tbody>
  43.  
  44. </table>
  45.  
  46. </body>
  47. </html>

teacher.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h1>增加老师</h1>
  10.  
  11. <form action="/add_teacher/" method="POST">
  12. <p>老师名称: <input type="text" name="name"></p>
  13. <input type="submit">
  14. </form>
  15.  
  16. </body>
  17. </html>

add_page_teacher.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <h3>编辑老师班级</h3>
  10.  
  11. <form action="/edit_page_teacher/?tnid={{ tname.tid }}" method="post">
  12.  
  13. <p>老师名称:<input type="text" name="name" value="{{ tname.name }}"></p>
  14.  
  15. <p>班级名称:
  16. <select name="class_ids" multiple size="">
  17. {% for item in class_list %}
  18. {% if item.cid in class_ids %}
  19. <option selected value="{{ item.cid }}">{{ item.title }}</option>
  20. {% else %}
  21. <option value="{{ item.cid }}">{{ item.title }}</option>
  22. {% endif %}
  23. {% endfor %}
  24. </select>
  25.  
  26. <p><input type="submit" value="提交"></p>
  27. </p>
  28.  
  29. </form>
  30.  
  31. </body>
  32. </html>

edit_page_teacher.html

  1. ###网页显示
  2. def teacher(request):
  3.  
  4. teacher_list=sqlheper.get_list("""
  5. select teacher.tid as tid,teacher.name,class.title from teacher
  6. left join teacher_class on teacher_class.teacher_id=teacher.tid
  7. left join class on class.cid=teacher_class.class_id""",[])
  8. # print(teacher_list)
  9. result = {}
  10. for row in teacher_list:
  11. tid = row["tid"]
  12. if tid in result:
  13. result[tid]["titles"].append(row["title"])
  14. else:
  15. result[tid] = {"tid":row["tid"],"name":row["name"],"titles":[row["title"],]}
  16.  
  17. class_list = sqlheper.get_list("select cid,title from class",[])
  18.  
  19. return render(request, "teacher.html", {"teacher_list":result.values(), "class_list":class_list})
  20.  
  21. ###网页增加
  22. def add_page_teacher(request):
  23. if request.method=="GET":
  24. obj = sqlheper.SqlHelper()
  25. class_list = obj.get_list("select cid,title from class",[])
  26. obj.close()
  27. return render(request,"add_page_teacher.html",{"class_list":class_list})
  28. else:
  29.  
  30. name = request.POST.get("name")
  31. obj = sqlheper.SqlHelper()
  32. teacher_id = obj.get_lastrowid("insert into teacher(name) values(%s)",[name,])
  33. obj.close()
  34.  
  35. class_ids = request.POST.getlist("class_ids")
  36. print(class_ids)
  37.  
  38. data_list = []
  39. for cls_id in class_ids:
  40. temp = (teacher_id, cls_id,)
  41. data_list.append(temp)
  42.  
  43. obj = sqlheper.SqlHelper()
  44. obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)', data_list)
  45. obj.close()
  46. return redirect('/teacher/')
  47.  
  48. ###网页编辑
  49. def edit_page_teacher(request):
  50. if request.method=="GET":
  51. teacher_id = request.GET.get("tid")
  52. obj = sqlheper.SqlHelper()
  53. tname = obj.get_one("select tid,name from teacher where tid=%s",[teacher_id,])
  54.  
  55. class_list = obj.get_list("select cid,title from class",[])
  56.  
  57. class_ids = obj.get_list("select class_id from teacher_class where teacher_id =%s",[teacher_id,])
  58. obj.close()
  59.  
  60. temp = []
  61. for i in class_ids:
  62. temp.append(i['class_id'])
  63.  
  64. return render(request,"edit_page_teacher.html",{
  65. "tname":tname,
  66. "class_list":class_list,
  67. "class_ids":temp,
  68. })
  69. else:
  70. tid=request.GET.get("tnid")
  71. name=request.POST.get("name")
  72. class_ids=request.POST.getlist("class_ids")
  73.  
  74. obj = sqlheper.SqlHelper()
  75. obj.modify("update teacher set name=%s where tid=%s",[name,tid,])
  76. obj.modify('delete from teacher_class where teacher_id=%s',[tid,])
  77. data_list = []
  78. for cls_id in class_ids:
  79. temp = (tid,cls_id)
  80. data_list.append(temp)
  81. obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)',data_list)
  82. obj.close()
  83. return redirect('/teacher/')

views.py

5.多对多 老师 班级 模态  增加 编辑

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. .hide{
  8. display: none;
  9. }
  10. .shadow{
  11. position: fixed;
  12. top: 0;
  13. bottom: 0;
  14. left: 0;
  15. right: 0;
  16. background-color: black;
  17. z-index: 999;
  18. opacity: 0.4;
  19. }
  20. .loading{
  21. position: fixed;
  22. width: 32px;
  23. height: 32px;
  24. left: 50%;
  25. top:50%;
  26. margin-left: -16px;
  27. margin-top: -16px;
  28. background-color: rebeccapurple;
  29. background-image: url("/static/images/loading.gif") ;
  30. background-size: 100%;
  31.  
  32. }
  33. .Modal{
  34. position: fixed;
  35. top: 50%;
  36. left: 50%;
  37. width: 400px;
  38. height: 300px;
  39. margin-left: -200px;
  40. margin-top: -150px;
  41. z-index: 1000;
  42. background-color: white;
  43. }
  44. </style>
  45. <link rel="stylesheet" href="/static/plugins/bootstrap-3.3.7-dist/css/bootstrap.css">
  46. <link rel="stylesheet" href="/static/plugins/font-awesome-4.7.0/css/font-awesome.css">
  47. </head>
  48. <body>
  49.  
  50. <h1 >老师 班级管理</h1>
  51.  
  52. <div class="btn btn-success">
  53.  
  54. <a id="addModal">模态框增加</a>
  55. </div>
  56.  
  57. <table border="solid" class="table table-striped">
  58. <thead>
  59. <tr>
  60. <td>ID</td>
  61. <td>老师名称</td>
  62. <td>班级名称</td>
  63. <td>操作</td>
  64. </tr>
  65. </thead>
  66. <tbody>
  67. {% for row in teacher_list %}
  68. <tr>
  69. <td>{{ row.tid }}</td>
  70. <td>{{ row.name }}</td>
  71. <td>
  72. {% for item in row.titles %}
  73. {{ item }}
  74. {% endfor %}
  75. </td>
  76. <td>
  77. <a class="editModal">编辑</a>
  78. <a class="delModal">删除</a>
  79. </td>
  80. </tr>
  81. {% endfor %}
  82. </tbody>
  83.  
  84. </table>
  85.  
  86. <div id="shadow" class="shadow hide"></div>
  87.  
  88. <div id="loading" class="loading hide"></div>
  89.  
  90. <div id="add_tea_cls" class="Modal hide">
  91.  
  92. <p>老师名称:
  93. <input id="add_name" type="text" name="add_name">
  94. </p>
  95.  
  96. <p>班级名称:
  97. <select id="add_classId" name="add_classId" multiple size="">
  98.  
  99. </select>
  100. </p>
  101. <input id="btnAdd" type="button" value="提交"><span id="addError"></span>
  102. <input id="btnCancle" type="button" value="取消">
  103.  
  104. </div>
  105.  
  106. <div id="edit_tea_cls" class="Modal hide">
  107. <input type="text" id="hide_id" style="display: none">
  108.  
  109. <p>老师名称:
  110. <input id="edit_name" type="text" name="add_name">
  111. </p>
  112.  
  113. <p>班级名称:
  114. <select id="edit_classId" name="edit_classId" multiple size="">
  115.  
  116. </select>
  117. </p>
  118. <input id="btnEdit" type="button" value="提交"><span id="addError"></span>
  119. <input id="cacleEdit" type="button" value="取消">
  120.  
  121. </div>
  122.  
  123. <script src="/static/jquery-3.2.1.js"></script>
  124.  
  125. <script>
  126.  
  127. $(function () {
  128.  
  129. {# 增加#}
  130. $("#addModal").click(function () {
  131. $("#shadow,#loading").removeClass("hide");
  132. $.ajax({
  133. url:"/get_all_class/",
  134. type:"GET",
  135. dataType:"JSON",
  136. success:function (arg) {
  137. $.each(arg,function (i,row) {
  138. var tag = $("<option>"); /*var tag = document.createElement('option');*/
  139. tag.text(row.title); /*tag.innerHTML = row.title;*/
  140. tag.prop("value",row.cid);
  141. $("#add_classId").append(tag); /*tag.setAttribute('value',row.id);*/
  142. });
  143. $('#loading').addClass('hide');
  144. $('#add_tea_cls').removeClass('hide');
  145. }
  146. })
  147. });
  148.  
  149. $("#btnCancle").click(function () {
  150. $("#shadow,#add_tea_cls").addClass("hide");
  151. });
  152.  
  153. $("#btnAdd").click(function () {
  154. var tname=$("#add_name").val();
  155. var class_list=$("#add_classId").val();
  156. console.log(class_list);
  157. $.ajax({
  158. url:"/new_teacher/",
  159. type:"POST",
  160. data:{"tname":tname,"class_list":class_list},
  161. dataType:"JSON",
  162. traditional: true, // 如果提交的数据的值有列表,则需要添加此属性
  163. success:function (arg) {
  164.  
  165. if (arg.status){
  166. location.reload();
  167. }else {
  168. alert(arg.message);
  169. }
  170. }
  171. })
  172. });
  173.  
  174. {# 编辑#}
  175. $(".editModal").click(function () {
  176. $("#shadow,#loading").removeClass("hide");
  177. var ids=$(this).parent().prevAll()[2];
  178. var id=$(ids).text();
  179. $("#hide_id").val(id);
  180. $.ajax({
  181. url: "/edit_tea_cls/",
  182. type: "POST",
  183. dataType: "JSON",
  184. data:{"id":id},
  185. success: function (arg) {
  186.  
  187. class_list = arg[0];
  188. teacher_info = arg[1];
  189. class_lds = arg[2];
  190. console.log(class_lds);
  191. $("#edit_classId").empty();
  192. $.each(class_list, function (i, row) {
  193. var tag = $("<option>");
  194. tag.text(row.title);
  195. tag.prop("value", row.cid);
  196.  
  197. if(class_lds.indexOf(row.cid) == -1){
  198. $("#edit_classId").append(tag);
  199. }else {
  200. tag.prop("selected","selected");
  201. $("#edit_classId").append(tag);
  202. }
  203. });
  204. $("#edit_name").val(teacher_info["name"]);
  205.  
  206. $('#loading').addClass('hide');
  207. $('#edit_tea_cls').removeClass('hide');
  208. }
  209. });
  210.  
  211. $("#cacleEdit").click(function () {
  212. $("#shadow,#edit_tea_cls").addClass("hide");
  213. });
  214. })
  215.  
  216. {# 编辑提交#}
  217. $("#btnEdit").click(function () {
  218. var tid= $("#hide_id").val();
  219. var name = $("#edit_name").val();
  220. var class_ids = $("#edit_classId").val();
  221. $.ajax({
  222. url:"/modal_edit_teacher/",
  223. type:"post",
  224. dataType:"JSON",
  225. traditional:true,
  226. data:{"tid":tid,"name":name,"del_class_id":del_class_id},
  227. $.ajax({
  228. url:"/modal_edit_teacher/",
  229. type:"post",
  230. dataType:"JSON",
  231. traditional:true,
  232. data:{"tid":tid,"name":name,"class_ids":class_ids},
  233. success:function (arg) {
  234. if (arg.status){
  235. location.reload();
  236. }else {
  237. alert("")
  238. }
  239. }
  240. })
  241. })
  242. })
  243. })
  244.  
  245. </script>
  246.  
  247. </body>
  248. </html>

teacher.html

  1. #显示
  2. def teacher(request):
  3.  
  4. tk = request.COOKIES.get("ticket")
  5. if not tk:
  6. return redirect("/login/")
  7.  
  8. teacher_list=sqlheper.get_list("""
  9. select teacher.tid as tid,teacher.name,class.title from teacher
  10. left join teacher_class on teacher_class.teacher_id=teacher.tid
  11. left join class on class.cid=teacher_class.class_id""",[])
  12. # print(teacher_list)
  13. result = {}
  14. for row in teacher_list:
  15. tid = row["tid"]
  16. if tid in result:
  17. result[tid]["titles"].append(row["title"])
  18. else:
  19. result[tid] = {"tid":row["tid"],"name":row["name"],"titles":[row["title"],]}
  20.  
  21. return render(request, "teacher.html", {"teacher_list":result.values()})
  22.  
  23. #增加
  24. def get_all_class(request):
  25. import time
  26. time.sleep(1)
  27. obj = sqlheper.SqlHelper()
  28. class_list = obj.get_list('select cid,title from class',[])
  29. obj.close()
  30. return HttpResponse(json.dumps(class_list))
  31.  
  32. def new_teacher(request):
  33.  
  34. ret = {'status': True, 'message': None}
  35. try:
  36. class_list=request.POST.getlist("class_list")
  37. tname=request.POST.get("tname")
  38. teacher_id=sqlheper.get_IncrementId("insert into teacher(name) values(%s)",[tname,])
  39.  
  40. data_list = []
  41. for cls_id in class_list:
  42. temp = (teacher_id,cls_id,)
  43. data_list.append(temp)
  44.  
  45. obj = sqlheper.SqlHelper()
  46. obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)', data_list)
  47. obj.close()
  48. except Exception as e:
  49. ret['status'] = False
  50. ret['message'] = str(e)
  51. return HttpResponse(json.dumps(ret))
  52.  
  53. #编辑
  54. def edit_tea_cls(request):
  55.  
  56. id = request.POST.get("id")
  57. obj = sqlheper.SqlHelper()
  58. class_list = obj.get_list('select cid,title from class',[])
  59.  
  60. teacher_info = obj.get_one("select tid,name from teacher where tid=%s",[id,])
  61.  
  62. class_id = obj.get_list("select class_id from teacher_class where teacher_id=%s",[id,])
  63.  
  64. data_list = []
  65. for cls_id in class_id:
  66. data_list.append(cls_id["class_id"])
  67.  
  68. print(teacher_info)
  69. total = []
  70. total.append(class_list)
  71. total.append(teacher_info)
  72. total.append(data_list)
  73. obj.close()
  74. return HttpResponse(json.dumps(total))
  75.  
  76. def modal_edit_teacher(request):
  77. ret = {'status': True, 'message': None}
  78. try:
  79. name = request.POST.get("name")
  80. tid = request.POST.get("tid")
  81. class_ids = request.POST.getlist("class_ids")
  82.  
  83. obj = sqlheper.SqlHelper()
  84. obj.modify("update teacher set name=%s where tid=%s", [name, tid, ])
  85. obj.modify('delete from teacher_class where teacher_id=%s', [tid, ])
  86. data_list = []
  87. for cls_id in class_ids:
  88. temp = (tid, cls_id)
  89. data_list.append(temp)
  90. obj.multiple_modify('insert into teacher_class(teacher_id,class_id) values(%s,%s)', data_list)
  91. obj.close()
  92. except Exception as e:
  93. ret['status'] = False
  94. ret['message'] = str(e)
  95. return HttpResponse(json.dumps(ret))

views.py

Django 相亲小项目

用户登录  如果男用户登录,显示女生列表

          如果女用户登录,显示男生列表
  1. from django.shortcuts import render,HttpResponse,redirect
  2. from app01 import models
  3.  
  4. def login(request):
  5. if request.method == "GET":
  6. return render(request,"login.html")
  7. else:
  8. username = request.POST.get("username")
  9. password = request.POST.get("password")
  10. gender = request.POST.get("gender")
  11. if gender == "":
  12. obj = models.Boy.objects.filter(username=username,password=password).first()
  13. else:
  14. obj = models.Girl.objects.filter(username=username,password=password).first()
  15. if not obj:
  16. #未登录
  17. return render(request,"login.html",{"msg":"用户名或密码错误"})
  18. else:
  19. request.session["user_info"] = {"user_id":obj.id,"gender":gender,"username":username,"nickname":obj.nickname}
  20. return redirect("/index.html")
  21.  
  22. def logout(request):
  23. if request.session.get("user_info"):
  24. request.session.clear()
  25. return redirect("/login.html")

views/account.py

  1. from django.shortcuts import render,HttpResponse,redirect
  2. from app01 import models
  3.  
  4. def index(request):
  5. if not request.session.get("user_info"):
  6. return redirect("/login.html")
  7. else:
  8. gender = request.session.get("user_info").get("gender")
  9. if gender == "":
  10. user_list = models.Girl.objects.all()
  11. else:
  12. user_list = models.Boy.objects.all()
  13. return render(request,"index.html",{"user_list":user_list})
  14.  
  15. def others(request):
  16.  
  17. current_user_id = request.session.get("user_info").get("user_id")
  18. gender = request.session.get("user_info").get("gender")
  19. if gender == "":
  20. user_list = models.B2G.objects.filter(b_id=current_user_id).values("g__nickname")
  21. else:
  22. user_list = models.B2G.objects.filter(g_id=current_user_id).values("b__nickname")
  23. return render(request,"other.html",{"user_list":user_list})
  24.  
  25. def test(request):
  26.  
  27. # models.Boy.objects.create(nickname="方少伟",username="fsw",password="123")
  28. # models.Boy.objects.create(nickname="陈涛",username="ct",password="123")
  29. # models.Boy.objects.create(nickname="egon",username="egon",password="123")
  30. #
  31. # models.Girl.objects.create(nickname="lili", username="lili", password="123")
  32. # models.Girl.objects.create(nickname="jim", username="jim", password="123")
  33. # models.Girl.objects.create(nickname="xiaojie", username="xiaojie", password="123")
  34.  
  35. # models.B2G.objects.create(b_id=1,g_id=1)
  36. # models.B2G.objects.create(b_id=1,g_id=2)
  37. # models.B2G.objects.create(b_id=1,g_id=3)
  38. # models.B2G.objects.create(b_id=2,g_id=1)
  39. # models.B2G.objects.create(b_id=3,g_id=1)
  40. # models.B2G.objects.create(b_id=4,g_id=1)
  41.  
  42. return HttpResponse("...")

views/love.py

  1. from django.db import models
  2.  
  3. # Create your models here.
  4.  
  5. class Boy(models.Model):
  6. nickname = models.CharField(max_length=32)
  7. username = models.CharField(max_length=32)
  8. password = models.CharField(max_length=64)
  9.  
  10. class Girl(models.Model):
  11. nickname = models.CharField(max_length=32)
  12. username = models.CharField(max_length=32)
  13. password = models.CharField(max_length=64)
  14.  
  15. class B2G(models.Model):
  16. b = models.ForeignKey(to="Boy",to_field="id")
  17. g = models.ForeignKey(to="Girl",to_field="id")

models.py

  1. urlpatterns = [
  2. url(r'^admin/', admin.site.urls),
  3.  
  4. url(r'^test.html$', love.test),
  5.  
  6. url(r'^login.html$', account.login),
  7. url(r'^logout.html$', account.logout),
  8.  
  9. url(r'^index.html$', love.index),
  10. url(r'^others.html$', love.others),
  11.  
  12. ]

urls.py

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. <form action="/login.html" method="POST">
  10. {% csrf_token %}
  11. <p>用户:<input type="text" name="username"></p>
  12. <p>密码:<input type="password" name="password"></p>
  13. <p>
  14. 性别:
  15. <input type="radio" name="gender" value="">
  16. <input type="radio" name="gender" value="">
  17. </p>
  18.  
  19. <input type="submit" value="提交">{{ msg }}
  20. </form>
  21.  
  22. </body>
  23. </html>

login.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. {% include "user_head.html" %}
  10.  
  11. <h3>异性列表</h3>
  12. <a href="/others.html">查看和我有关系的异性</a>
  13. <ul>
  14. {% for row in user_list %}
  15. <li>{{ row.nickname }}</li>
  16. {% endfor %}
  17. </ul>
  18.  
  19. </body>
  20. </html>

index.html

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8.  
  9. {% include "user_head.html" %}
  10.  
  11. <h3>有关系的异性列表</h3>
  12. <ul>
  13. {% for row in user_list %}
  14. {% if row.g__nickname %}
  15. <li>{{ row.g__nickname }}</li>
  16. {% else %}
  17. <li>{{ row.b__nickname }}</li>
  18. {% endif %}
  19. {% endfor %}
  20. </ul>
  21.  
  22. </body>
  23. </html>

other.html

  1. <h3>当前用户: {{ request.session.user_info.nickname }}</h3>
  2. <a href="/logout.html">注销</a>

user_head.html

Django小项目练习的更多相关文章

  1. Python之路【第十八篇】Django小项目简单BBS论坛部分内容知识点

    开发一个简单的BBS论坛 项目需求: 整体参考“抽屉新热榜” + “虎嗅网” 实现不同论坛版块 帖子列表展示 帖子评论数.点赞数展示 在线用户展示 允许登录用户发贴.评论.点赞 允许上传文件 帖子可被 ...

  2. Django小项目简单BBS论坛

    开发一个简单的BBS论坛 项目需求: 1 整体参考"抽屉新热榜" + "虎嗅网" 2 实现不同论坛版块 3 帖子列表展示 4 帖子评论数.点赞数展示 5 在线用 ...

  3. Python之路【第十八篇】Django小项目webQQ实现

    WEBQQ的实现的几种方式 1.HTTP协议特点 首先这里要知道HTTP协议的特点:短链接.无状态! 在不考虑本地缓存的情况举例来说:咱们在连接博客园的时候,当tcp连接后,我会把我自己的http头发 ...

  4. Django小项目web聊天

    WEBQQ的实现的几种方式 1.HTTP协议特点 首先这里要知道HTTP协议的特点:短链接.无状态! 在不考虑本地缓存的情况举例来说:咱们在连接博客园的时候,当tcp连接后,我会把我自己的http头发 ...

  5. django小项目,使用paramiko自动备份网络设备配置

    原来公司开发团队人员众多,有专门对接运维需求的开发人员,现在想要实现些功能可(只)以(能)自己写了-_- |   周末在家无事,用django搞个简单的功能练练手 django安装,配置 sudo p ...

  6. Django 小实例S1 简易学生选课管理系统 0 初步介绍与演示

    Django 小实例S1 简易学生选课管理系统 第0章--初步介绍与演示 点击查看教程总目录 作者自我介绍:b站小UP主,时常直播编程+红警三,python1对1辅导老师. 1 初步介绍 先介绍下这个 ...

  7. Django集成celery实战小项目

    上一篇已经介绍了celery的基本知识,本篇以一个小项目为例,详细说明django框架如何集成celery进行开发. 本系列文章的开发环境: window 7 + python2.7 + pychar ...

  8. python3开发进阶-Django框架学习前的小项目(一个简单的学员管理系统)

    ''' 自己独立写一个学员管理系统 表结构: 班级表: -id -grade_name 学生表: -id -student_name -grade 关联外键班级表 老师表: -id -teacher_ ...

  9. Django 小实例S1 简易学生选课管理系统 2 新建项目(project)并进行设置

    Django 小实例S1 简易学生选课管理系统 第2节--新建项目(project)并进行设置 点击查看教程总目录 作者自我介绍:b站小UP主,时常直播编程+红警三,python1对1辅导老师. 0 ...

随机推荐

  1. HDU——1846Brave Game(巴什博弈)

    Brave Game Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total ...

  2. HDU——1205吃糖果(鸽巢原理)

    吃糖果 Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 65535/32768 K (Java/Others) Total Submis ...

  3. 【FFT】学习笔记

    首先,多项式有两种表示方式,系数表示和点值表示 对于两个多项式相乘而言,用系数表示进行计算是O(n^2)的 而用点值表示进行计算是O(n)的 那么我们自然就会去想如果把系数表示的多项式转化为点值表示的 ...

  4. POJ3349 Snowflake Snow Snowflakes 【哈希表】

    题目 很简单,给一堆6元组,可以从任意位置开始往任意方向读,问有没有两个相同的6元组 题解 hash表入门题 先把一个六元组的积 + 和取模作为hash值,然后查表即可 期望\(O(n)\) #inc ...

  5. java面试题之什么是CAS

    CAS,即Compare and Switch,比较-替换,里面有三个操作数:内存值V.旧的预期值A.要修改的值B: 当预期值A和内存值V相同时,才会将内存值修改为B并返回true,否则什么都不做并返 ...

  6. cf496D Tennis Game

    Petya and Gena love playing table tennis. A single match is played according to the following rules: ...

  7. web 工程中利用Spring的 ApplicationContextAware接口自动注入bean

    最常用的办法就是用 ClassPathXmlApplicationContext, FileSystemClassPathXmlApplicationContext, FileSystemXmlApp ...

  8. spring-boot项目热部署以及spring-devtools导致同类不能转换

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring- ...

  9. 洛谷 P 1387 最大正方形

    题目描述 在一个n*m的只包含0和1的矩阵里找出一个不包含0的最大正方形,输出边长. 输入输出格式 输入格式: 输入文件第一行为两个整数n,m(1<=n,m<=100),接下来n行,每行m ...

  10. 应用js函数柯里化currying 与ajax 局部刷新dom

    直接上代码吧 最近读javascript核心概念及实践的代码 感觉很有用 备忘. <div id="request"></div> <script t ...