Django中的装饰器,分页,
2018-10-15 本文已影响0人
He
装饰器:
加入要给一些界面加一个登录权限:
直接上代码
在utils里面:
#装饰器,判断用户是否登录
def require_login(fn):
def inner(request,*args, **kwargs):
if request.session.has_key("loginUser"):
logging.warning("该用户已经登录,视图函数正常访问")
return fn(request, *args, **kwargs)
else:
logging.warning("请先登录!!")
return render(request,"demo/login.html", {"msg": "当前操作必须登录,请先登录系统"})
return inner
然后在views里面可以直接调用
分页:
django提供了一个非常简单的分页方法,直接上代码:
from django.core.paginator import Paginator
def index(request):
# logger = logging.getLogger("django")
#logger.warning("首页开始运行了……")
#在缓存中获取数据
articles = cacheUtils.getAllArticle()
pageSize = int(request.GET.get("pageSize", settings.PAGE_SIZE))
pageNow = int(request.GET.get("pageNow", 1))
paginator = Paginator(articles, pageSize)
page = paginator.page(pageNow)
return render(request, "blog/index1.html", {"page": page, "pageSize": pageSize})
在前端界面上:
<div class="col-md-8">
<!--<div class="page-header">-->
<!--<h3>热门文章 <small>这里能找到技术前沿的各位大神的文章内容</small></h3>-->
<!--</div>-->
<div class="row author-article">
<div class="tab-content">
<div role="tabpanel" class="tab-pane active" id="home">
{% for at in page.object_list %}
<div class="media">
<div class="media-body">
<h4 class="media-heading"><a href="{% url 'demo:show_article' at.id %}">{{at.title}}</a></h4>
{{at.content | safe}}
</div>
<div class="media-left media-middle">
<a href="#">
<img class="media-object " src="/static/demo/image/articles/1.jpg" alt="图片">
</a>
</div>
<div class="media-bottom text-muted">
<span class="glyphicon glyphicon-eye-open">169</span>
<span class="glyphicon glyphicon-comment">18</span>
<span class="glyphicon glyphicon-heart">200</span>
<span> {{at.publishtime}}</span>
</div>
</div>
{% endfor %}
</div>
<nav aria-label="Page navigation">
<ul class="pagination">
{% if page.has_previous %}
<li>
<a href="/demo/index?page_now={{page.previous_page_number}}" aria-label="Previous">
<span aria-hidden="true">«</span>
</a>
</li>
{% endif %}
{% for p in page.paginator.page_range %}
<li><a href="/demo/index/?page_now={{p}}">{{p}}</a></li>
{% endfor %}
{% if page.has_next %}
<li>
<a href="/demo/index?page_now={{page.next_page_number}}" aria-label="Next">
<span aria-hidden="true">»</span>
</a>
</li>
{% endif %}
</ul>
</nav>
</div>
</div>
</div>
基本上都是固定用法,可以直接照搬代码。