django构建blog--页面部分(eclipse+pydev)

时间:2023-10-07 15:26:26

本文介绍的是在eclipse+pydev 平台下,利用django 搭建blog的第2部分:页面部分(主要涉及3个部分:模板、视图、URL模式)

篇幅1:创建模板

blog目录下新建一个文件夹:templates,添加archive.html文件,让其显示所有blog的内容,代码如下:

	{% for post in posts %}
<h2>{{post.title}}</h2>
<p>{{post.timestamp}}</p>
<p>{{post.body}}</p>
{% endfor %}

  

篇幅2:创建视图函数

from blog.models import BlogPost
from django.template import Context,loader
from django.http import HttpResponse # Create your views here. def archive(request):
posts=BlogPost.objects.all()
t=loader.get_template("archive.html")
c=Context({'posts':posts})
return HttpResponse(t.render(c))

篇幅3:创建一个URL模式

1 myweb.urls.py文件进行编辑如下:

from django.conf.urls import include, url
from django.contrib import admin urlpatterns = [
# Examples:
# url(r'^$', 'myweb.views.home', name='home'),
url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)),
]

2 在blog下新建urls.py文件,并进行编辑,如下:

#coding=utf-8
from django.conf.urls import url,patterns
from blog.views import archive urlpatterns=patterns('',
url(r'^$',archive) )

 

访问页面查看效果:http://127.0.0.1:8000/blog/

django构建blog--页面部分(eclipse+pydev)

篇幅4: 优化页面-模板+日期显示和排序

1. 设置一个base.html模板,templates下新建base.html文件,编辑如下:

 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<style>
body{color:#efd;background:#453;padding:0.5em;margin:0}
h2{color:#bf8;border-top:1px dotted #fff;margin-top:2em}
p{} </style>
</head>
<body>
{%block content%}
{%endblock%}
</body>
</html>

2. 修改archive.html模板,让其引用base.html模板和它的“content”块,编辑如下:

 <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
<title></title>
</head>
<body>
{%extends "base.html"%}
{%block content%}
{% for post in posts %}
<h2>{{post.title}}</h2>
<p>{{post.timestamp"}}</p>
<p>{{post.body}}</p>
{% endfor %}
{%endblock%}
</body>
</html>

再次访问页面:http://127.0.0.1:8000/blog/

django构建blog--页面部分(eclipse+pydev)

3. 按日期排序,修改blog.models.py文件,增加如下代码class Meta:ordering=('-timestamp',)

from django.db import models
from django.contrib import admin # Create your models here.
class BlogPost(models.Model):
title=models.CharField(max_length=)
body=models.TextField()
timestamp=models.DateTimeField()
class Meta:
ordering=('-timestamp',) class BlogPostAdmin(admin.ModelAdmin):
list_display=('title','timestamp') admin.site.register(BlogPost,BlogPostAdmin)

查看页面

4. 优化日期显示,属于表现层的内容,修改archive.html文件中日期部分即可

<p>{{post.timestamp|date:"Y-m-d H:i:s"}}</p>

 

django构建blog--页面部分(eclipse+pydev)