You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
55 lines
1.4 KiB
55 lines
1.4 KiB
from django.http import JsonResponse,HttpResponse |
|
from django.shortcuts import render |
|
|
|
from blog.models import Blog |
|
from django.core.paginator import Paginator # 引入分页功能 |
|
|
|
|
|
''' |
|
url中传入两个参数: page(页号)和page_size(每页最多记录数) |
|
参数错误时使用默认值 |
|
''' |
|
def blog_list(request): |
|
# 默认第1页 |
|
page = request.GET.get('page', 1) |
|
# 每页默认为20条 |
|
page_size = request.GET.get('page_size', 20) |
|
# 所有blog记录 |
|
blog_qs = Blog.objects.all() |
|
# 根据页号和每页最多记录数提取对应记录 |
|
paginator = Paginator(blog_qs, page_size) |
|
current_page = paginator.get_page(page) |
|
|
|
blogs = current_page.object_list |
|
|
|
resp = { |
|
'blog_list': [ |
|
{ |
|
'id': blog.id, |
|
'title': blog.title, |
|
} for blog in blogs |
|
] |
|
} |
|
return HttpResponse(resp.values()) |
|
|
|
|
|
def blog_detail(request,blog_id): |
|
blog = Blog.objects.get(id=blog_id) |
|
resp = { |
|
'blog': [ |
|
{ |
|
'id': blog.id, |
|
'title': blog.title, |
|
'content': blog.content, |
|
'author': { |
|
'id': blog.author.id, |
|
'username': blog.author.username, |
|
} |
|
} |
|
] |
|
} |
|
return HttpResponse(resp.values()) |
|
|
|
|
|
def index(request): |
|
return render(request, 'blog/index.html') |