zoukankan      html  css  js  c++  java
  • day-60Django

    项目跟进

    服务器:

    ### 查看班级
    def classes(request):
        print(request.COOKIES)
    
        v1 = request.COOKIES.get('k1')
        if not v1:
            return redirect('/login/')
    
        import pymysql
        conn = pymysql.connect(host='127.0.0.1', user='root',  password='123', db='s8day58', charset='utf8')
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        sql = "select * from classes"
        cursor.execute(sql)
        classes = cursor.fetchall()                               #当classes.html需要班级列表是,在这里传过去
    
        return render(request, "classes.html", {"classes":classes})
    def ajax_add_student(request): stuname = request.POST.get('stuname') classid = request.POST.get('classid') print(stuname, classid) ret = {"code":None, "data":None} try: sql = "insert into students (name, class_id) values (%s, %s)" sqlhelper.insert(sql, (stuname, classid)) #这里也可以lastrowid拿到插入数据的主键id,在传给html ret['code'] = 10000 ret['data'] = "success" except Exception as e: ret['code'] = 10001 ret['data'] = str(e) return HttpResponse(json.dumps(ret)) ### 留作业 def ajax_up_student(request): pass def teachers(request): sql = "select teacher.id as tid , teacher.name as tname, teacher2class.cid as cid, classes.name as cname from teacher left join teacher2class on teacher.id = teacher2class.tid left join classes on classes.id = teacher2class.cid;" #三表联查,选出有用的数据(多对多,两张表的数据都重复,就建第三张表) teachers = sqlhelper.getAll(sql) print(teachers) res = {} for item in teachers: tid = item['tid'] if tid in res: res[tid]['cnames'].append(item['cname']) else: res[tid] = {"tid": tid, 'tname': item['tname'], 'cnames': [item['cname'], ]} return render(request, "teachers.html", {"teachers":res.values()}) def add_teacher(request): if request.method == 'GET': sql = "select * from classes" classes = sqlhelper.getAll(sql) return render(request, "add_teacher.html", {"classes":classes}) else: ## 作业 tname = request.POST.get('tname') classid = request.POST.getlist('classid') select(multiple) option 标签    #从select获取多个值: classid = request.POST.getlist('classid') print(tname) print(classid) 作业思路 ### 1. tname需要添加到teacher表中 最后一个lastrowid ### 2. teacher2class (lastrowid, 2), (lastrowid, 3), (lastrowid, 7) ====> executeMany() return HttpResponse('ok') def layout(request): return render(request, "layout.html") def login(request): if request.method == 'GET': return render(request, "login.html") else: username = request.POST.get('username') pwd = request.POST.get('pwd') if username == 'zekai' and pwd == '123': # from datetime import datetime # ct = datetime.utcnow() #当前时间 # from datetime import timedelta # t = timedelta(seconds=10) #为时间增,减时间 obj = redirect('/index/') obj.set_cookie("k1", "ndsjandjsanjdsanjdknsajdnsajndjsad",) return obj else: return render(request, "login.html") def index(request): return render(request, "main.html") def li1(request): obj = HttpResponse('li1') obj.set_cookie("xxxx", "dbshabdjsabdsadsadsadasdsa", path='/li1') return obj # 设置path,cookie只有li1能解析,别的路由解析不了 def li2(request): print(request.COOKIES) obj = HttpResponse('li2') # HTTPResponse也可以设置cookie # obj.set_cookie("li2", "thisisli2") return obj

    students.html:

         <table border="1px">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>姓名</th>
                        <th>班级</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {% for item in students %}
                        <tr>
                            <td>{{ item.id }}</td>
                            <td>{{ item.sname }}</td>
                            <td clsid="{{ item.cid }}">{{ item.cname }}</td>            #把clsid当做存放数据的容器,方便后面判断
                            <td>
                                <a href="/del_student/?id={{ item.id }}"  onclick="return xxxxx()">删除</a>|
                                <a href="/up_student/?id={{ item.id }}">更新</a>
                                <button class="ajax_student_modal">ajax更新</button>
                            </td>
                        </tr>
                    {% endfor %}
                </tbody>
            </table>

    teacher.html:

    <table class="table table-bordered  table-hover">
            <thead>
                <tr>
                    <th>ID</th>
                    <th>老师名</th>
                    <th>所教班级</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                {% for item in teachers %}
                    <tr>
                        <td>{{ item.tid }}</td>
                        <td>{{ item.tname }}</td>
                        <td>
                            {% for cname in item.cnames %}                    #循环展示列表
                                <span style="display:inline-block; border: 1px solid red;">{{ cname }}</span>
                            {% endfor %}                                      #display:block 行内标签也可以使用border
                        </td>
                        <td>
                            <a href="/del_class/?id={{ item.tid }}"  onclick="return xxxxx()" class="btn btn-danger">删除</a>|
                            <i class="fa fa-trash" aria-hidden="true"></i> <a href="/up_class/?id={{ item.tid }}">更新</a>
                            <button class="ajax_class_modal">ajax更新</button>
                        </td>
                    </tr>
                {% endfor %}
            </tbody>
        </table>

     模板语言中的母版和子板

    子版:
      布局页面: layout.html

      继承母版: {% extends "layout.html" %}


    母版:
    替换占位符:
      三个占位符
        内容占位符:
          {% block mycontent %}
          {% endblock %}


        css占位符:
          {% block mycss %}
          {% endblock %}
        js占位符:
          {% block myjs %}
          {% endblock %}

    django中cookie

    cookie:
      登陆成功之后, 设置cookie:
      obj = redirect('/classes/')
      obj.set_cookie("k1", "ndsjandjsanjdsanjdknsajdnsajndjsad")
      return obj


    set_cookie参数:
    key:
    value:
    max_age=None,       cookie过期时间
    expires=None       cookie过期时间(繁琐)
    path='/'          设置path,cookie只有本路由能解析,别的路由解析不了

    domain=“baidu.com”    设置域名
      mail.baidu.com    二级域名就可以访问百度,其他不行
      yun.baidu.com

    secure=False :     https访问改为true

    httponly=False :     只能在http中传递(true), 不能使用js获取cookie
                js获取cookie:
                  document.cookie

    对cookie加密:

      set_signed_cookie(key, val, salt(盐))

    总结:


      (原始)第一次访问登记下,下次访问看登记,有就给进去
      (现在)第一次访问,登记下,并给一个小纸条,这个纸条只有我们俩能看懂,下次来直接看纸条就行了


      验证成功,1.在本子上记录下(session)保存在服务器,2.传回一个我俩认识的小纸条(cookie),保存在浏览器,

      如果跳转页面失败继续验证


      服务端有cookie拦截,下次访问带着cookie就行了
      当服务端验证成功后,需要跳转服务器哪个html,哪个路由就需要验证cookie,防止能直接访问

      cookie是可以被禁用掉的

    补充

    - ajax :
      dataType : "json" ==   作用相当于 JSON.parse()


    - select:
      第二种默认选中方法:

        当设置value等于一个值时,展现的就是这个值对应的名字

         $('#editstu').val(clsid);

      返回给服务器的时候,获取多个值:

         classid = request.POST.getlist('classid') 

    模板语言的判断:
      {% for item in data %}
        {% if 表达式 %}
          代码
        {%elif%}
          代码
        {% else %}
          代码
        {%endfor%}


    注:"classes.html"表示在服务器列表查html
      "/classes/"表示浏览器访问服务器的url后面跟这个




  • 相关阅读:
    MongoDB Shell
    mongo 日记
    java 堆栈 静态
    面向对象(2)
    面向对象(1)
    mongo 学习笔记
    深入浅出学Spring Data JPA
    java记录
    mongodb 2.6 window 安装启动服务
    CF1012F Passports
  • 原文地址:https://www.cnblogs.com/klw1/p/11179216.html
Copyright © 2011-2022 走看看