Django显示博客文章内容

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengqiuming/article/details/85018817

一 编辑mysite/blog/views.py

from django.shortcuts import render, get_object_or_404

from .models import BlogArticles
# 基于函数的视图,这个函数叫视图函数
# 函数的参数是request,这个参数负责响应所接受到的请求且不能缺少
# 并总位于第一的位置,还可以根据需要在后面增加别的参数。
def blog_title(request):
    # 得到所有的BlogArticles对象实例。
    blogs = BlogArticles.objects.all()
    # 将数据渲染到指定模板上。
    # 第1个参数必须是request
    # 然后是模板位置和所传达的数据。
    # 数据是用字典形式传达给模板的。
    return render(request, "blog/titles.html", {"blogs":blogs})

# 多了一个参数,该参数用于传递文章的id
def blog_article(request, article_id):
    #rticle = BlogArticles.objects.get(id=article_id)
    # 简化对请求网页不存在时的异常处理。
    article = get_object_or_404(BlogArticles, id=article_id)
    pub = article.publish
    return render(request, "blog/content.html", {"article":article, "publish":pub })

二 编辑mysite/blog/urls.py

from django.conf.urls import url
from . import views

urlpatterns = [
    url(r"^$", views.blog_title, name="blog_title"),
    url(r'(?P<article_id>\d)/$', views.blog_article, name="blog_article"),
]

三 新增mysite/blog/templates/blog/content.html

{% extends "base.html" %}
{% block title %}博客文章{% endblock %}
{% block content %}
<div class="row text-center vertical-middle-sm">
    <h1>{{ article.title }}</h1>
</div>
<div class="row">
    <div class="col-xs-12 col-md-8">
        <p class="text-center">
            <span>{{ article.author.username }}</span>
            <span style="margin-left:20px">{{ publish }}</span>
        </p>
        <div>{{ article.body }}</div>
    </div>
    <div class="col-xs-6 col-md-4">
        <h2>欢迎访问我的CSDN</h2>
        <p>https://blog.csdn.net/chengqiuming</p>
        <img width="200px" src="https://avatar.csdn.net/9/E/A/1_chengqiuming.jpg?1544877778">
    </div>
</div>
{% endblock %}

四 测试

1 访问存在的数据

2 访问不存在的数据

猜你喜欢

转载自blog.csdn.net/chengqiuming/article/details/85018817