Models 内容
# -*- coding: utf-8 -*-
from django.db import models
# Create your models here.
#DoubanModels 表示继承models
class DoubanModels(models.Model):
#id = models.AutoField(primary_key=True)
title = models.CharField(max_length=100,null=False)
content = models.TextField(null=False)
link = models.CharField(max_length=100, null= False
对应数据库表:
View视图中函数内容:
# print('Hello!!!!')
# 保存数据 需要后面的.SAVE 否则保存不到数据库
# DoubanModels(title='我是电影5', content='5', link='5').save()
# 取出当前表中所有数据 通过循环获取表中的记录
# for obj in DoubanModels.objects.all():
# print(obj.title)
# 取单条记录中的某个字段的值
# print(DoubanModels.objects.get(id=3).title )
# 1.打开青态页面
# return HttpResponse(open('templates/movie.html').read())
# 2.以下一样的打开页面
#return HttpResponse(render(request, 'movie.html'))
# return HttpResponse('Hello jango')
def index(request):
#批量往数据库中插入记录
#for i in range(6,66):
# DoubanModels(title='我是电影'+str(i), content=str(i), link=str(i)).save()
#return HttpResponse(render(request,'movie.html', context={'movies': DoubanModels.objects.all()}))
#获取前15条记录 ---进行切片处理
return HttpResponse(render(request, 'movie.html', context={'movies': DoubanModels.objects.all()[:15]}))
#return HttpResponse('Hello jango')
#添加上默认的参数;分页
def page(request,page):
#pass
page = int(page) # 转换为数字
if page == 0:
page =1
return HttpResponse(render(request, 'movie.html', context={'movies': DoubanModels.objects.all()[(page-1)*15:page*15],'up': page-1,'down': page+1}))
模板页内容
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<H1>hello django---xibei</H1>
<div>
{% for i in movies %}
<li> {{ i.title }}</li>
{% endfor %}
</div>
<div>
<a href="/page/list_{{ up }}.html">上一页</a>
<a href="/page/list_{{ down }}.html">下一页</a>
</div>
</body>
</html>
显示结果:
URL内容
from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from douban import views
urlpatterns = [
#path('admin/', admin.site.urls),
url(r'^admin/', admin.site.urls),
url(r'^$', views.index),
url(r'^page/list_(\d+).html$',views.page), #list_(\d+).html 表示必须出现一个数字
]