python实战计划 Django 的模板语言

  1. 理解上下文
  2. 使用模板语言
  3. 制作分页器

#Note

##理解上下文

###views.py

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

###models.py

from mongoengine import *

##模板语言

1
2
3
{ % 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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. 加载当前页
1
2
3
4
5
6
7
8
9
10
11
12
13
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} }代替
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
{% 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&#x27;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

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

index.html__生成页码

1
2
3
4
5
6
7
8
9
</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>

总结

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

文章目录
  1. 1. Code
    1. 1.1. models.py
    2. 1.2. views.py
    3. 1.3. index.html__生成条目
    4. 1.4. index.html__生成页码
  2. 2. 总结