Django学习之视图与模板(二)

在上一篇中,初步学习了Django视图和模块,今天继续深入学习它。

到目前为止,我们能显示所有博客在一个页面,但是我们同时也想单独显示某一篇博客。

首先,我们来修改模块blog/templates/blog/index.html,为每个博客标题添加一个链接,这样我们才能跳转到某篇博客。

<!DOCTYPE html>
<html>
    <head>
        <title>My Blog</title>
    </head>
    <body>
        {% if blogs %}
        {% for blog in blogs %}
        <a href={% url 'detail' blog.id %}><h2>{{blog.title}}</h2></a>
        <p>Published {{blog.published_time}}</p>
        <p>{{blog.text | linebreaks}}</p>
        {% endfor %}
        {% else %}
        <p>No blog was published</p>
        {% endif %}
    </body>
</html>

下面,我们运行开发服务器python manage.py runserver,在浏览器中输入http://127.0.0.1:8000/blogs/,然后我们点击某篇博客的标题,结果如下:

怎么回事?仔细看一下页面的调试信息。哦原来是URL找不到任何的匹配(The current URL, blogs/4, didn't match any of these.)。那我们就来修改一下URL配置。添加一条能够获取博客文章ID的匹配,然后将此HttpRequest和此ID一同传递给视图函数detail。

from django.conf.urls import patterns,url

from blog import views

urlpatterns = patterns('',
    url(r'^$',views.index,name='index'),
    url(r'^(?P<id>d+)/$',views.detail,name='detail'),
)

接着,我们再重新运行开发服务器python manage.py runserver,在浏览器中输入http://127.0.0.1:8000/blogs/,然后我们点击某篇博客的标题,结果如下:

咦,又报错,模块没有属性detail。哦,我们得添加一个视图函数,修改blog/views。

from django.shortcuts import render,get_object_or_404
from blog.models import Blog

def index(request):
    blogs=Blog.objects.all()
    return render(request,'blog/index.html',{'blogs':blogs})


def detail(request,id):
    blog=get_object_or_404(Blog,pk=id)
    return render(request,'blog/detail.html',{'blog':blog})

注意,我们在上面的视图函数中,用到了一个新的模块get_object_or_404,顾名思义,就是获取对象,如果获取不到,那么返回404页面。我们来看一下detail函数的参数,第一个是httprequest对象,第二个参数是通过URL匹配获取的。

恩,注意到视图函数,我们调用了一个新的模板文件detail.html,因此我们得编辑它,编辑blog/templates/blog/detail.html后保存。

<!DOCTYPE html>
<html>
    <head>
        <title>My blog</title>
    </head>
    <body>
        <a href='#'><h1>{{blog.title}}</h1></a>
        <p>Published {{blog.published_time}}</p>
        <p>{{blog.text|linebreaks}}</p>
    </body>
</html>

恩,我们重启服务器,在浏览器中输入http://127.0.0.1:8000/blogs/回车,完了,我们再点击某篇博客标题

这样我们就能查看某一特定博客的页面了。

原文地址:https://www.cnblogs.com/tmyyss/p/4373650.html