Django+xadmin打造在线教育平台(十一)
十、首页模块
1、首页展示
(1)、视图函数
def index(request): all_banners = BannerInfo.objects.all().order_by('-add_time')[:5] banner_courses = CourseInfo.objects.filter(is_banner=True)[:3] all_courses = CourseInfo.objects.filter(is_banner=False)[:6] all_orgs = OrgInfo.objects.all()[:15] return render(request, 'index.html', { 'all_banners': all_banners, 'bannner_courses': banner_courses, 'all_courses': all_courses, 'all_orgs': all_orgs })
(2)、前端页面
{% extends 'base.html' %} {% load staticfiles %} {% block title %} 首页 — 谷粒教育 {% endblock %} {% block content %} <div class="banner"> <div class="wp"> <div class="fl"> <div class="imgslide"> <ul class="imgs"> {% for banner in all_banners %} <li> <a href="{{ banner.url }} "> <img width="1200" height="478" src="{{ MEDIA_URL }}{{ banner.image }}" /> </a> </li> {% endfor %} </ul> </div> <div class="unslider-arrow prev"></div> <div class="unslider-arrow next"></div> </div> </div> </div> <section> <div class="wp"> <ul class="feature"> <li class="feature1"> <img class="pic" src="{% static 'images/feature5.png' %}"/> <p class="center">专业权威</p> </li> <li class="feature2"> <img class="pic" src="{% static 'images/feature5.png' %}"/> <p class="center">课程最新</p> </li> <li class="feature3"> <img class="pic" src="{% static 'images/feature5.png' %}"/> <p class="center">名师授课</p> </li> <li class="feature4"> <img class="pic" src="{% static 'images/feature5.png' %}"/> <p class="center">数据真实</p> </li> </ul> </div> </section> <section> <div class="module"> <div class="wp"> <h1>公开课程</h1> <div class="module1 eachmod"> <div class="module1_1 left"> <img width="228" height="614" src="{% static 'images/module5_1.jpg' %}"/> <p class="fisrt_word">名师授课<br/>专业权威</p> <a class="more" href="{% url 'courses:course_list' %}">查看更多课程 ></a> </div> <div class="right group_list"> <div class="module1_2 box"> <div class="imgslide2"> <ul class="imgs"> {% for banner in all_banners %} <li> <a href="{% url 'courses:course_detail' banner.id %}"> <img width="470" height="300" src="{{ MEDIA_URL }}{{ banner.image }}" /> </a> </li> {% endfor %} </ul> </div> <div class="unslider-arrow2 prev"></div> <div class="unslider-arrow2 next"></div> </div> {% for cours in all_courses %} <div class="module1_{{ forloop.counter|add:"2" }} box"> <a href="{% url 'courses:course_detail' cours.id %}"> <img width="233" height="190" src="{{ MEDIA_URL }}{{ cours.image }}"/> </a> <div class="des"> <a href="{% url 'courses:course_detail' cours.id %}"> <h2 title="{{ cours.name }}">{{ cours.name }}</h2> </a> <span class="fl">难度:<i class="key"> {% if cours.level == 'gj' %}高级 {% elif cours.level == 'zj' %} 中级 {% else %} 初级 {% endif %} </i></span> <span class="fr">学习人数:{{ cours.study_num }}</span> </div> <div class="bottom"> <span class="fl" title="{{ cours.orginfo.name }}">{{ cours.orginfo.name }}</span> <span class="star fr">{{ cours.love_num }}</span> </div> </div> {% endfor %} </div> </div> </div> </div> </section> <section> <div class="module greybg"> <div class="wp"> <h1>课程机构</h1> <div class="module3 eachmod"> <div class="module3_1 left"> <img width="228" height="463" src="{% static 'images/module6_1.jpg' %}"/> <p class="fisrt_word">名校来袭<br/>权威认证</p> <a class="more" href="{% url 'orgs:org_list' %}">查看更多机构 ></a> </div> <div class="right"> <ul> {% for org in all_orgs %} <li {% if forloop.counter|divisibleby:"5" %} class="five" {% endif %}> <a href="{% url 'orgs:org_detail' org.id %}"> <div class="company"> <img width="184" height="100" src="{{ MEDIA_URL }}{{ org.image }}"/> <div class="score"> <div class="circle"> <h2>全国知名</h2> </div> </div> </div> <p><span class="key" title="{{ org.name }}">{{ org.name }}</span></p> </a> </li> {% endfor %} </ul> </div> </div> </div> </div> </section> {% endblock %}
index.html
2、全局模糊搜索
全局模糊搜索用到了Q方法,在base中写js代码,拼接url,并发起请求,
<script> $(function(){ $("#jsSearchBtn").click(function () { var search_type = $('#jsSelectOption').attr('data-value'); var key_word = $('#search_keywords').val(); var url = ''; if(search_type == 'org'){ url = "{% url 'orgs:org_list' %}" }else if(search_type == 'course'){ url = "{% url 'courses:course_list' %}" }else{ url = "{% url 'orgs:teacher_list' %}" } url = url + '?keyword='+ key_word; window.location.href=url }); }) </script>
<!DOCTYPE html> {% load staticfiles %} <html> <head> <meta charset="UTF-8"> <meta name="renderer" content="webkit"> <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1" > <title>{% block title %} {% endblock %}</title> <link rel="stylesheet" type="text/css" href="{% static 'css/reset.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/animate.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> {% block mycss %} {% endblock %} <script src="{% static 'js/jquery.min.js' %}" type="text/javascript"></script> <script src="{% static 'js/jquery-migrate-1.2.1.min.js' %}" type="text/javascript"></script> </head> <body> <section class="headerwrap"> <header> <div class=" header header2"> <div class="top"> <div class="wp"> <div class="fl"><p>服务电话:<b>8888888</b></p></div> <!--登录后跳转--> {% if request.user.is_authenticated %} <div class="personal"> <dl class="user fr"> <dd>{{ request.user.username }}<img class="down fr" src="{% static 'images/top_down.png' %}"/></dd> <dt><img width="20" height="20" src="{{ MEDIA_URL }}{{ request.user.image }}"/></dt> </dl> <div class="userdetail"> <dl> <dt><img width="80" height="80" src="{{ MEDIA_URL }}{{ request.user.image }}"/></dt> <dd> <h2>{{ request.user.nick_name }}</h2> <p>{{ request.user.username }}</p> </dd> </dl> <div class="btn"> <a class="personcenter fl" href="{% url 'users:user_info' %}">进入个人中心</a> <a class="fr" href="{% url 'users:logout' %}">退出</a> </div> </div> </div> <a href="{% url 'users:user_message' %}"> <div class="msg-num"><span id="MsgNum">{{ request.user.get_msg_counter }}</span></div> </a> {% else %} <a style="color:white" class="fr registerbtn" href="{% url 'users:register' %}">注册</a> <a style="color:white" class="fr loginbtn" href="{% url 'users:login' %}">登录</a> {% endif %} </div> </div> {% block middle %} <div class="middle"> <div class="wp"> <a href="/"><img class="fl" src="{% static 'images/logo1.png' %}"/></a> <div class="searchbox fr"> <div class="selectContainer fl"> <span class="selectOption" id="jsSelectOption" data-value="course"> 公开课 </span> <ul class="selectMenu" id="jsSelectMenu"> <li data-value="course">公开课</li> <li data-value="org">课程机构</li> <li data-value="teacher">授课老师</li> </ul> </div> <input id="search_keywords" class="fl" type="text" value="" placeholder="请输入搜索内容"/> <img class="search_btn fr" id="jsSearchBtn" src="{% static 'images/search_btn.png' %}"/> </div> </div> </div> <nav> <div class="nav"> <div class="wp"> <ul> <li {% if request.path == '/' %} class="active" {% endif %}><a href="/">首页</a></li> <li {% if request.path|slice:':9' == '/courses/' %} class="active" {% endif %}> <a href="{% url 'courses:course_list' %}"> 公开课<img class="hot" src="{% static 'images/nav_hot.png' %}"> </a> </li> <li {% if request.path|slice:':13' == '/orgs/teacher' %} class="active" {% endif %}> <a href="{% url 'orgs:teacher_list' %}">授课教师</a> </li> <li {% if request.path|slice:':9' == '/orgs/org' %} class="active" {% endif %}><a href="{% url 'orgs:org_list' %}">授课机构</a></li> </ul> </div> </div> </nav> {% endblock %} </div> </header> </section> {% block content %} {% endblock %} {% block footer %} <footer> <div class="footer"> <div class="wp"> <ul class="cont"> <li class="logo"><a href=""><img src="{% static 'images/logo1.png' %}"/></a></li> <li class="code"><img src="{% static 'images/code.jpg' %}"/><p class="center">扫描关注微信</p></li> <li class="third"><img class="fl" src="{% static 'images/tell.png' %}"/><p class="tell">88888888</p><p class="time">周一至周日 9:00-18:00</p></li> </ul> </div> <p class="line"></p> <div class="wp clear"> <span class="fl">? 2012 www.atguigu.com谷粒教育-在线学习交流平台 保留所有权利</span> <span class="fr">copyright ? 2012 ICP备案证书号:蜀ICP备xxxxx号-1</span> </div> </div> </footer> {% endblock %} <section> <ul class="sidebar"> <li class="qq"> <a target="_blank" href="/"></a> </li> <li class="totop"></li> </ul> </section> <script src="{% static 'js/selectUi.js' %}" type='text/javascript'></script> <script src="{% static 'js/deco-common.js' %}" type='text/javascript'></script> <script type="text/javascript" src="{% static 'js/plugins/laydate/laydate.js' %}"></script> <script src="{% static 'js/plugins/layer/layer.js' %}"></script> <script src="{% static 'js/plugins/queryCity/js/public.js' %}" type="text/javascript"></script> <script src="{% static 'js/unslider.js' %}" type="text/javascript"></script> <script src="{% static 'js/plugins/jquery.scrollLoading.js' %}" type="text/javascript"></script> <script src="{% static 'js/deco-common.js' %}" type="text/javascript"></script> <script type="text/javascript" src="{% static 'js/index.js' %}"></script> <script> $(function(){ $("#jsSearchBtn").click(function () { var search_type = $('#jsSelectOption').attr('data-value'); var key_word = $('#search_keywords').val(); var url = ''; if(search_type == 'org'){ url = "{% url 'orgs:org_list' %}" }else if(search_type == 'course'){ url = "{% url 'courses:course_list' %}" }else{ url = "{% url 'orgs:teacher_list' %}" } url = url + '?keyword='+ key_word; window.location.href=url }); }) </script> {% block myjs %} {% endblock %} </body> </html>
base.html
后端分别在机构列表,讲师列表以及课程列表中分别加入查询方法。
并在对应的前端分页代码中加入相应的关键字keyword。
def org_list(request): all_orgs = OrgInfo.objects.all() # 获取所有的机构 all_citys = CityInfo.objects.all() # 获取所有的城市 sort_orgs = all_orgs.order_by('-love_num')[:3] # 对机构排序并取三个 # 全局搜索功能过滤 keyword = request.GET.get('keyword', '') if keyword: # 在全局进行模糊查询 all_orgs = all_orgs.filter(Q(name__icontains=keyword)|Q(desc__icontains=keyword)|Q(detail__icontains=keyword)) # 按照机构类别过滤 cate = request.GET.get('cate', '') if cate: all_orgs = all_orgs.filter(category=cate) # 按照所在地区过滤筛选 cityid = request.GET.get('cityid', '') if cityid: all_orgs = all_orgs.filter(cityinfo_id=int(cityid)) # 一对多,多的一方查询id # 排序 sort = request.GET.get('sort', '') if sort: all_orgs = all_orgs.order_by('-'+sort) # 分页功能 pagenum = request.GET.get('pagenum', '') pa = Paginator(all_orgs, 4) try: pages = pa.page(pagenum) except PageNotAnInteger: pages = pa.page(1) except EmptyPage: pages = pa.page(pa.num_pages) return render(request, 'orgs/org-list.html', { 'all_orgs': all_orgs, 'all_citys': all_citys, 'sort_orgs': sort_orgs, 'pages': pages, 'cate': cate, 'cityid': cityid, 'sort': sort, 'keyword': keyword, })
def teacher_list(request): all_teachers = TeacherInfo.objects.all() sort_teachers = all_teachers.order_by('-love_num')[:2] # 全局搜索功能过滤 keyword = request.GET.get('keyword', '') if keyword: # 在全局进行模糊查询 all_teachers = all_teachers.filter( Q(name__icontains=keyword)) sort = request.GET.get('sort') if sort: all_teachers = all_teachers.order_by('-' + sort) # 分页 pagenum = request.GET.get('pagenum', '') pa = Paginator(all_teachers, 2) try: pages = pa.page(pagenum) except PageNotAnInteger: pages = pa.page(1) except EmptyPage: pages = pa.page(pa.num_pages) return render(request, 'orgs/teachers-list.html', { 'all_teachers': all_teachers, 'sort_teachers': sort_teachers, 'pages': pages, 'sort': sort, 'keyword': keyword })
def course_list(request): all_course = CourseInfo.objects.all() recommond_course = all_course.order_by('-add_time')[:3] # 全局搜索功能过滤 keyword = request.GET.get('keyword', '') if keyword: # 在全局进行模糊查询 all_course = all_course.filter( Q(name__icontains=keyword) | Q(desc__icontains=keyword) | Q(detail__icontains=keyword)) sort = request.GET.get('sort', '') if sort: all_course = all_course.order_by('-'+sort) # 分页功能 pagenum = request.GET.get('pagenum', '') pa = Paginator(all_course, 3) try: pages = pa.page(pagenum) except PageNotAnInteger: pages = pa.page(1) except EmptyPage: pages = pa.page(pa.num_pages) return render(request, 'courses/course-list.html', { 'all_course': all_course, 'recommond_course': recommond_course, 'pages': pages, 'sort': sort, 'keyword': keyword })
{% extends 'base.html' %} {% block title %} 公开课列表 - 谷粒教育网 {% endblock %} {% block content %} <section> <div class="wp"> <ul class="crumbs"> <li><a href="/">首页</a>></li> <li>公开课</li> </ul> </div> </section> <section> <div class="wp"> <div class="list" style="margin-top:0;"> <div class="left layout"> <div class="head"> <ul class="tab_header"> <li {% if sort == '' %}class="active"{% endif %}><a href="?sort=">最新 </a></li> <li {% if sort == 'click_num' %}class="active"{% endif %}><a href="?sort=click_num" >最热门</a></li> <li {% if sort == 'study_num' %}class="active"{% endif %}><a href="?sort=study_num">参与人数</a></li> </ul> </div> <div id="inWindow"> <div class="tab_cont " id="content"> <div class="group_list"> {% for course in pages %} <div class="box"> <a href="{% url 'courses:course_detail' course.id %}"> <img width="280" height="350" class="scrollLoading" src="{{ MEDIA_URL }}{{ course.image }}"/> </a> <div class="des"> <a href="{% url 'courses:course_detail' course.id %}"> <h2>{{ course.name }}</h2> </a> <span class="fl">时长:<i class="key">{{ course.study_time }}</i></span> <span class="fr">学习人数:{{ course.study_num }}</span> </div> <div class="bottom"> <a href="{% url 'courses:course_detail' course.id %}"><span class="fl">{{ course.orginfo.name }}</span></a> <span class="star fr notlogin " data-favid="15"> {{ course.love_num }} </span> </div> </div> {% endfor %} </div> <div class="pageturn"> <ul class="pagelist"> {% if pages.has_previous %} <li class="long"><a href="?pagenum={{ pages.previous_page_number }}&sort={{ sort }}&keyword={{ keyword }}">上一页</a></li> {% endif %} {% for num in pages.paginator.page_range %} <li {% if num == pages.number %} class="active" {% endif %}><a href="?pagenum={{ num }}&sort={{ sort }}&keyword={{ keyword }}">{{ num }}</a></li> {% endfor %} {% if pages.has_next %} <li class="long"><a href="?pagenum={{ pages.next_page_number }}&sort={{ sort }}&keyword={{ keyword }}">下一页</a></li> {% endif %} </ul> </div> </div> </div> </div> <div class="right layout"> <div class="head">热门课程推荐</div> <div class="group_recommend"> {% for course in recommond_course %} <dl> <dt> <a target="_blank" href="{% url 'courses:course_detail' course.id %}"> <img width="240" height="220" class="scrollLoading" src="{{ MEDIA_URL }}{{ course.image }}"/> </a> </dt> <dd> <a target="_blank" href="{% url 'courses:course_detail' course.id %}"><h2> {{ course.name }}</h2></a> <span class="fl">难度: <i class="key"> {% if course.level == 'cj' %} 初级 {% elif course.level == 'zj' %} 中级 {% else %} 高级 {% endif %} </i> </span> </dd> </dl> {% endfor %} </div> </div> </div> </div> </section> {% endblock %}
course-list.html
{% extends 'base.html' %} {% block title %} 课程讲师 - 谷粒教育网 {% endblock %} {% block content %} <section> <div class="wp"> <ul class="crumbs"> <li><a href="/">首页</a>></li> <li>课程讲师</li> </ul> </div> </section> <section> <div class="wp butler_list_box list"> <div class='left'> <div class="butler_list layout"> <div class="head"> <ul class="fl tab_header"> <li {% if sort == '' %} class="active" {% endif %}><a href="?sort=">全部</a> </li> <li {% if sort == 'click_num' %} class="active" {% endif %}><a href="?sort=click_num">人气 ↓</a></li> </ul> <div class="fr butler-num">共<span class="key">{{ all_teachers.count }}</span>人 </div> </div> {% for teacher in pages %} <dl class="des"> <dt> <a href="{% url 'orgs:teacher_detail' teacher.id %}"> <div class="picpic"> <img width="100" height="100" class="scrollLoading" src="{{ MEDIA_URL }}{{ teacher.image }}"/> </div> </a> <div class="btn"> <div class="fr btn2 bdsharebuttonbox"> <span class="fl">分享</span> <a href="#" class="bds_more" data-cmd="more"></a> </div> </div> </dt> <dd> <a href="{% url 'orgs:teacher_detail' teacher.id %}"> <h1>{{ teacher.name }}<span class="key picbig">金牌讲师</span></h1> </a> <ul class="cont"> <li>工作年限:<span>{{ teacher.work_year }}年</span></li> <li>工作职位:<span>{{ teacher.work_position }}</span></li> <li>就职公司:<span>{{ teacher.work_company.name }} </span></li> <li>年龄:<span>{{ teacher.age }}岁</span></li> <li>教学特点:<span>{{ teacher.work_style }}</span></li> </ul> </dd> <a class="buy buyservice" href="{% url 'orgs:teacher_detail' teacher.id %}"><br/>查看<br/>详情</a> </dl> {% endfor %} </div> <div class="pageturn"> <ul class="pagelist"> {% if pages.has_previous %} <li class="long"><a href="?pagenum={{ pages.previous_page_number }}&sort={{ sort }}&keyword={{ keyword }}">上一页</a></li> {% endif %} {% for num in pages.paginator.page_range %} <li {% if num == pages.number %} class="active" {% endif %}><a href="?pagenum={{ num }}&sort={{ sort }}&keyword={{ keyword }}">{{ num }}</a></li> {% endfor %} {% if pages.has_next %} <li class="long"><a href="?pagenum={{ pages.next_page_number }}&sort={{ sort }}&keyword={{ keyword }}">下一页</a></li> {% endif %} </ul> </div> </div> <div class="right layout"> <div class="head">讲师排行榜</div> {% for teacher in sort_teachers %} <dl class="des"> <span class="num fl">{{ forloop.counter }}</span> <a href="{% url 'orgs:teacher_detail' teacher.id %}"> <dt> <img width="50" height="50" class="scrollLoading" src="{{ MEDIA_URL }}{{ teacher.image }}"/> </dt> </a> <dd> <a href="{% url 'orgs:teacher_detail' teacher.id %}"> <h1 title="{{ teacher.name }}">{{ teacher.name }}</h1> </a> <p>工作年限:<span>{{ teacher.work_year }}年</span></p> </dd> </dl> {% endfor %} </div> </div> </section> {% endblock %}
teacher-list.html
{% extends 'base.html' %} {% load staticfiles %} {% block title %} 课程机构列表 - 谷粒教育网 {% endblock %} {% block content %} <section> <div class="wp"> <ul class="crumbs"> <li><a href="{% url 'index' %}">首页</a>></li> <li>课程机构</li> </ul> </div> </section> <section> <div class="wp butler_list_box list"> <div class='left'> <div class="listoptions"> <ul> <li> <h2>机构类别</h2> <div class="cont"> <a href="?&cityid={{ cityid }}&sort={{ sort }}"><span {% if cate == "" %} class="active2" {% endif %}>全部</span></a> <a href="?cate=pxjg&cityid={{ cityid }}&sort={{ sort }}"><span {% if cate == "pxjg" %} class="active2" {% endif %}>培训机构</span></a> <a href="?cate=gx&cityid={{ cityid }}&sort={{ sort }}"><span {% if cate == "gx" %} class="active2" {% endif %}>高校</span></a> <a href="?cate=gr&cityid={{ cityid }}&sort={{ sort }}"><span {% if cate == "gr" %} class="" {% endif %}>个人</span></a> </div> </li> <li> <h2>所在地区</h2> <div class="more">更多</div> <div class="cont"> <a href="?"><span {% if cityid == "" %}class="active2" {% endif %}>全部</span></a> {% for city in all_citys %} <a href="?cityid={{ city.id }}&sort={{ sort }}"><span {% if cityid == city.id|stringformat:"i" %} class="active2" {% endif %}>{{ city }}</span></a> {% endfor %} </div> </li> </ul> </div> <div class="all">共<span class="key">{{ all_orgs.count }}</span>家</div> <div class="butler_list company list"> <div class="layout"> <div class="head"> <ul class="tab_header"> <li {% if sort == '' %} class="active" {% endif %}><a href="?cityid={{ cityid }}&cate={{ cate }}">全部</a> </li> <li {% if sort == 'study_num' %} class="active" {% endif %}><a href="?sort=study_num&cityid={{ cityid }}&cate={{ cate }}">学习人数 ↓</a></li> <li {% if sort == 'course_num' %} class="active" {% endif %}><a href="?sort=course_num&cityid={{ cityid }}&cate={{ cate }}">课程数 ↓</a></li> </ul> </div> {% for org in pages %} <dl class="des difdes"> <dt> <a href="{% url 'orgs:org_detail' org.id %}"> <img width="200" height="120" class="scrollLoading" data-url="{{ MEDIA_URL }}{{ org.image }}"/> </a> </dt> <dd> <div class="clearfix"> <a href="{% url 'orgs:org_detail' org.id %}"> <h1>{{ org.name }}</h1> <div class="pic fl"> <img src="{% static 'images/authentication.png' %}"/> <img src="{% static 'images/gold.png' %}"/> </div> </a> </div> <ul class="cont"> <li class="first"><p class="pic9">课程数:<span>{{ org.course_num }}</span></p><p class="c7">学习人数:<span>{{ org.study_num }}</span></p></li> <li class="c8" style="padding-left:18px;">{{ org.address }}</li> <li class="pic10" style="padding-left:18px;">经典课程: {% for course in org.courseinfo_set.all|slice:"3" %} <a href="{% url 'courses:course_detail' course.id %}">{{ course.name }}</a> {% endfor %} </li> </ul> </dd> <div class="buy start_groupbuy jsShowPerfect2" data-id="22"><br/>联系<br/>服务</div> </dl> {% endfor %} </div> <div class="pageturn"> <ul class="pagelist"> {% if pages.has_previous %} <li class="long"><a href="?pagenum={{ pages.previous_page_number }}&cate={{ cate }}&cityid={{ cityid }}&sort={{ sort }}&keyword={{ keyword }}">上一页</a></li> {% endif %} {% for num in pages.paginator.page_range %} <li {% if num == pages.number %} class="active" {% endif %}><a href="?pagenum={{ num }}&cate={{ cate }}&cityid={{ cityid }}&sort={{ sort }}&keyword={{ keyword }}">{{ num }}</a></li> {% endfor %} {% if pages.has_next %} <li class="long"><a href="?pagenum={{ pages.next_page_number }}&cate={{ cate }}&cityid={{ cityid }}&sort={{ sort }}&keyword={{ keyword }}">下一页</a></li> {% endif %} </ul> </div> </div> </div> <div class="right companyright"> <div class="head">我要学习</div> <form class="rightform" id="jsStayForm" > <div> <img src="{% static 'images/rightform1.png' %}"/> <input type="text" name="name" id="companyName" placeholder="名字" maxlength="25" /> </div> <div> <img src="{% static 'images/rightform2.png' %}"/> <input type="text" name="mobile" id="companyMobile" placeholder="联系电话"/> </div> <div> <img src="{% static 'images/rightform3.png' %}"/> <input type="text" name="course_name" id="companyAddress" placeholder="课程名" maxlength="50" /> </div> <p class="error company-tips" id="jsCompanyTips"></p> <input class="btn" type="submit" id="jsStayBtn" value="立即咨询 >" /> </form> </div> <div class="right companyrank layout"> <div class="head">授课机构排名</div> {% for org in sort_orgs %} <dl class="des"> <dt class="num fl">{{ forloop.counter }}</dt> <dd> <a href="{% url 'orgs:org_detail' org.id %}"><h1>{{ org.name }}</h1></a> <p>{{ org.cityinfo.name }}</p> </dd> </dl> {% endfor %} </div> </div> </section> {% endblock %} {% block myjs %} <script> $(function () { $('#jsStayBtn').click(function () { {# 如果拿的是非表单的元素用text(),如果表单元素用val #} var name = $('#companyName').val(); var phone = $('#companyMobile').val(); var course = $('#companyAddress').val(); $.ajax({ type: 'POST', url: '{% url 'operations:user_ask' %}', data:{ "name": name, "phone": phone, "course":course, csrfmiddlewaretoken: '{{ csrf_token }}' }, success:function (callback) { if(callback.status == 'ok'){ alert(callback.msg); $('#jsCompanyTips').text(); $('#companyName').val(); $('#companyMobile').val(); $('#companyAddress').val(); }else{ alert(callback.msg); $('#jsCompanyTips').text(callback.msg) } } }); return false }) }) </script> {% endblock %}
org-list.html
十一、自定义装饰器实现验证用户登录
在某些时候,我们需要验证用户登录才能访问我们的页面,django提供了验证,但是django自身的验证存在局限,只能返回特定的页面,但是我们的需求是,用户访问需要登录的页面,验证用户是否登录,如果登录就正常访问,没有登录跳转到登录页面,登录成功后,返回刚才的页面,但是django自身的验证只能返回登录视图定义的返回页面,而且有些时候我们需要验证ajax请求,这时候自身的认证也不能满足我们的需求。
1、django自带的装饰器
from django.contrib.auth.decorators import login_required @login_required(login_url='/users/login/')
实现机制
from django.shortcuts import redirect,reverse from django.http import JsonResponse def login_decorator(func): def inner(request, *args, **kwargs): if request.user.is_authenticated: return func(request, *args, **kwargs) else: return redirect(reverse('users:user_login')) # 登录的url return inner
2、自定义升级版
from django.shortcuts import redirect,reverse from django.http import JsonResponse def login_decorator(func): def inner(request, *args, **kwargs): if request.user.is_authenticated: return func(request, *args, **kwargs) else: if request.is_ajax(): # 判断是否为ajax请求 return JsonResponse({'status': 'nologin'}) # 拿到目前访问的完整url,不只是路径部分 url = request.get_full_path() ret = redirect(reverse('users:user_login')) ret.set_cookie('url',url) return ret return inner
实现原理:取目前访问的完整url,存到cookie或者session,这里采用cookie,在登录的视图函数中取cookie,
验证ajax,只能返回登录页面,在js代码中判断callback.status的值。
def user_login(request): if request.method == 'GET': return render(request, 'users/login.html') else: user_login_form = UserLoginForm(request.POST) if user_login_form.is_valid(): # 判断是否合法 email = user_login_form.cleaned_data['email'] password = user_login_form.cleaned_data['password'] user = authenticate(username=email, password=password) # 验证邮箱密码 if user: if user.is_start: # 判断是否激活 login(request, user) # 登录 # 创造消息 # 当登录成功时候,加入一条消息 a = UserMessage() a.message_man = user.id a.message_content = '欢迎登录' a.save() url = request.COOKIES.get('url', '/') ret = redirect(url) ret.delete_cookie('url') return ret else: return HttpResponse('请去您的邮箱激活,否则无法登录') else: return render(request, 'users/login.html', { 'msg': '邮箱或密码有误' }) else: return render(request, 'users/login.html', { 'user_login_form': user_login_form })
3、实例
用户收藏的操作需要在登录等状态下。
@login_decorator def user_love(request): love_id = request.GET.get('loveid', '') love_type = request.GET.get('lovetype', '') if love_id and love_type: # 根据传过来的收藏类型,判断是什么对象,根据传递过来的收藏id,判断收藏的是哪个对象 obj = None if int(love_type) == 1: obj = OrgInfo.objects.filter(id=int(love_id))[0] if int(love_type) == 2: obj = CourseInfo.objects.filter(id=int(love_id))[0] if int(love_type) == 3: obj = TeacherInfo.objects.filter(id=int(love_id))[0] # 如果收藏的id和type同时存在,那么首先去收藏表中查找这个用户有没有这个收藏记录 love = UserLove.objects.filter(love_id=love_id, love_type=int(love_type), love_man=request.user) if love: # 如果本来已经存在收藏这个东西的记录,那么需要判断收藏的状态,如果为真,代表之前收藏过, # 并且现在的页面上应该显示的是取消收藏,代表这一次点击是为了取消收藏 if love[0].love_status: love[0].love_status = False love[0].save() obj.click_num -= 1 obj.save() return JsonResponse({ 'status': 'ok', 'msg': '收藏' }) else: # 如果收藏状态为假,代表之前收藏过,并且取消了收藏,现在页面上应该显示的是收藏,这次点击是为了收藏 love[0].love_status = True love[0].save() obj.click_num += 1 obj.save() return JsonResponse({ 'status': 'ok', 'msg': '取消收藏' }) else: # 如果之前没有收藏过这个东西,代表着表中没有这条记录,需要先创建这个记录对象,然后把这个记录的状态改为True a = UserLove() a.love_man = request.user a.love_id = int(love_id) a.love_type = int(love_type) a.love_status = True a.save() obj.click_num += 1 obj.save() return JsonResponse({ 'status': 'ok', 'msg': '取消收藏' }) else: return JsonResponse({ 'status': 'fail', 'msg': '收藏失败' })
# org-detail-base.html $('#love').click(function () { var loveid = {{ org.id }}; var lovetype = 1; $.ajax({ type: 'GET', 'url': '{% url 'operations:user_love' %}', data : { loveid:loveid, lovetype:lovetype }, success:function(callback){ if(callback.status == 'ok'){ $('#love').text(callback.msg) }else if(callback.status == 'nologin'){ window.location.href = '{% url 'users:login' %}' } else{ alter(callback.msg) } } }) })
-----
--
Django+xadmin打造在线教育平台(十一)的更多相关文章
- Django+xadmin打造在线教育平台(二)
三.xadmin后台管理 3.1.xadmin的安装 django2.0的安装(源码安装方式): https://github.com/sshwsfc/xadmin/tree/django2 把zip ...
- Django+xadmin打造在线教育平台(三)
五.完成注册.找回密码和激活验证码功能 5.1.用户注册 register.html拷贝到templates目录 (1)users/views.py class RegisterView(View): ...
- Django+xadmin打造在线教育平台(一)
目录 在线教育平台(一) 在线教育平台(二) 在线教育平台(三) 在线教育平台(四) 在线教育平台(五) 在线教育平台(六) 在线教育平台(七) 在线教育平台( ...
- Django+xadmin打造在线教育平台(八)
十一.用户信息 11.1.个人信息展示 (1)新建‘usercenter-bae.html’当母板 {% load staticfiles %} <!DOCTYPE html> <h ...
- Django+xadmin打造在线教育平台(四)
七.授课机构功能 7.1.模板继承 (1)创建母板 把org-list.html拷贝到templates目录下,新建base.html,剪切org-list.html内容到里面 再修改一下静态文件的地 ...
- Django+xadmin打造在线教育平台(六)
九.课程章节信息 9.1.模板和urls 拷贝course-comments.html 和 course-video.html放入 templates目录下 先改course-video.html,同 ...
- Django+xadmin打造在线教育平台(十)
十四.xadmin的进阶开发 14.1.权限管理 (1)用户权限 超级用户拥有所有权限,其它添加的用户默认没有任何权限 进后台添加一个用户“Editor1”,勾上“职员状态”后,这个用户才可以登录进后 ...
- Django+xadmin打造在线教育平台(五)
目录 在线教育平台(一) 在线教育平台(二) 在线教育平台(三) 在线教育平台(四) 在线教育平台(五) 在线教育平台(六) 在线教育平台(七) 在线教育平台( ...
- Django+xadmin打造在线教育平台(七)
十.授课教师 10.1.讲师列表页 拷贝teacher-list.html和teacher-detail.html到templates目录下 先改teacher-list.html,同样继承base. ...
- Django+xadmin打造在线教育平台(九)
目录 在线教育平台(一) 在线教育平台(二) 在线教育平台(三) 在线教育平台(四) 在线教育平台(五) 在线教育平台(六) 在线教育平台(七) 在线教育平台( ...
随机推荐
- [20190918]shrink space与ORA-08102错误.txt
[20190918]shrink space与ORA-08102错误.txt 1.环境:SCOTT@test01p> @ ver1PORT_STRING V ...
- Java面试中遇到的坑【篇二面试干货】
俗话说早起的鸟儿有虫吃,现在临年关越来越近,有跳槽的想法的同事也都打算年前做好功课年后入职,所谓年终奖拿了,工作换的也是水到渠成. 说到这里想必有同学要说了,年底了放着年终奖不拿为何要跳槽呢?这个就要 ...
- SpringBoot2.x项目pom.xml第一行报错
原来使用的是2.1.4 后来改成2.1.3 保存自动从新下载就好了 毕竟使用人数多 maven地址:https://mvnrepository.com/artifact/org.springfr ...
- JDOJ1100: Fix
题目大意 给你n个点,其中一些点是固定的,然后还有一些没有固定的,然后问你固定所有点所用的线段的最小长度是多少. 所谓固定,就是形如三角形的情况,就是两个固定的点向一个未固定的点连两条边,就能把未固定 ...
- Pwnable-cmd1
ssh cmd1@pwnable.kr -p2222 (pw:guest) 先看一下c的源码 #include <stdio.h> #include <string.h> in ...
- 简述ECMAScript6新增特性
1.变量 var 可以重复声明.只有函数级的作用域.存在变量提升 let 不能重复声明.有块级作用域.没有变量提升.变量 const 不能重复声明.具有块级作用域.常量 2.箭头函数 a.为了方便而存 ...
- day82_10_31celery的使用
1.缓存 当一些数据需要固定地且频繁访问数据库时,需要使用到接口缓存. 以轮播图为例,每个用户都会访问首页,首页的轮播图长时间不会改变,所以可以使用cache,将固定数据保存到缓存中(redis),第 ...
- 《淘宝数据库OceanBase SQL编译器部分 源码阅读--解析SQL语法树》
淘宝数据库OceanBase SQL编译器部分 源码阅读--解析SQL语法树 曾经的学渣 2014-06-05 18:38:00 浏览1455 云数据库Oceanbase OceanBase是 ...
- ShuffleNet:
ShuffleNet算法详解 论文:ShuffleNet: An Extremely Efficient Convolutional Neural Network for Mobile Devices ...
- JPA简介
JPA的学习 JPA是Java Persistence API的简称,中文名Java持久层API.是Java EE5.0平台中Sun为了统一持久层ORM框架而制定的一套标准,注意是一套标准,而不是具体 ...