美文网首页
python实战计划 Django 的模板语言

python实战计划 Django 的模板语言

作者: 载欣载奔 | 来源:发表于2016-08-16 16:12 被阅读0次
  1. 理解上下文
  2. 使用模板语言
  3. 制作分页器

Note

理解上下文

views.py

render(request,x.html,context) 传入三个函数
{{ id }} , context = {id1='',id2='', }

models.py

from mongoengine import *

模板语言

{% for i in Artinfo%}

{% endfor %}

分页器

from django.core.paginator import Paginator

Aim

用58的数据库和昨天的模板生成一个博客

Result

Code

html格式化 项目下载

models.py

  1. 链接数据库
  2. 写个类,里面所有属性和数据库条目名字同名
  3. meta = 'collection' : 'sheet_out'链接对于collection
from django.db import models
from mongoengine import *
from mongoengine import connect

connect('ilw',host='localhost',port = 27017) 


class ArtiInfo(Document):
    price = StringField() # 注意和数据库中的名字一样
    place = StringField()
    title = StringField()
    comment = StringField()
    url = StringField()
    meta = {'collection':'sheet_out'}
# if use list
# tags = ListField(StringField())

views.py

  1. 设置每页上限
  2. 生成一个翻页对象
  3. 加载当前页
from django.shortcuts import render
from django.core.paginator import Paginator
from django_web.models import ArtiInfo


def index(request):
    limit = 3
    paginator = Paginator(ArtiInfo.objects,limit)
    page = request.GET.get('page',1)

    loaded = paginator.page(page) # 注意这里是小写的
    content = {'ArtiInfo' : loaded} # 注意这里不能直接写字典
    return render(request,'index.html',content)

index.html__生成条目

  1. for && endear
  2. {{代替id}}代替
{% for it in ArtiInfo %}

<div class="posts">
  <h1 class="content-subhead">Recent Posts</h1>
  <section class="post">
    <header class="post-header">
      <img class="post-avatar" alt="Eric Ferraiuolo's avatar" height="48" width="48" src={% static "img/common/ericf-avatar.png" %}>

      <h2 class="post-title">{{ it.title }}</h2>

      <p class="post-meta">
        By <a class="post-author" href="#">{{ it.place }}</a> under <a class="post-category post-category-js" href="#">{{ it.comment }}</a>
      </p>
    </header>

    <div class="post-description">
      <p>
        <a href="{{ it.url }}"> {{ it.price }} </a>
      </p>
    </div>
  </section>
{% endfor %}

如果用到list

{% for tag in item.tags %}
    <span class="meta-cate">{{ tag }}</span>
{% endfor %}

index.html__生成页码

</div class = "main-content-pagitor">
{% if ArtiInfo.has_previous %}
    <a href="?page={{ ArtiInfo.previous_page_number }}">Pre</a>
{% endif %}
    <span>{{ ArtiInfo.number }} of {{ ArtiInfo.paginator.num_pages }}</span>
{% if ArtiInfo.has_next %}
    <a href="?page={{ ArtiInfo.next_page_number }}">Next</a>
{% endif %}
</div>

总结

这一章模板内容相对较多...不过对于自己博客理解加深了一层还是很开心啦~~

相关文章

网友评论

      本文标题:python实战计划 Django 的模板语言

      本文链接:https://www.haomeiwen.com/subject/gcmpsttx.html