1. 程式人生 > >搭建自己的部落格(三):簡單搭建首頁和詳情頁

搭建自己的部落格(三):簡單搭建首頁和詳情頁

上一篇我們建立了部落格表和標籤表以及超級使用者,那如何將建立的部落格通過網頁顯示出來呢?‘我們簡單的建立首頁和詳情頁。

1、新建html介面

首先建立在blog app下建立一個templates資料夾,這個資料夾用來放置前端頁面,注意資料夾名字必須是templates。

建立blog_list.html 檔案用來放部落格列表。建立blog_detail.html檔案用來放部落格詳情。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
<title>felix Blog</title> </head> <body> <div> <h3>felix Blog</h3> </div> <br/> </body> </html>
blog_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title
>部落格詳情</title> </head> <body> </body> </html>
blog_detail.html

2、建立是檢視函式

開啟blog下的views.py

from django.shortcuts import render_to_response, get_object_or_404
from .models import Blog


# Create your views here.

# 部落格列表
def blog_list(requests):
    context 
= { 'blogs': Blog.objects.all() } return render_to_response('blog_list.html', context) # 部落格詳情 def blog_detail(requests, blog_pk): context = { 'blog': get_object_or_404(Blog, pk=blog_pk) } return render_to_response('blog_detail.html', context)
views.py

這裡檢視函式中傳遞了引數給前端,所以得修改一下之前寫的前端程式碼,渲染檢視函式傳遞過來的資料。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>felix Blog</title>
</head>
<body>
<div>
    <h3>felix Blog</h3>
</div>
<br/>
{% for blog in blogs %}
    <a href="{% url 'blog_detail' blog.pk %}"><h3>{{ blog.title }}</h3></a>
    <p>{{ blog.content }}</p>
{% endfor %}
</body>
</html>
blog_list.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{{ blog.title }}</title>
</head>
<body>

<a href="{% url 'home' %}">
    <div>
        <h3>felix Blog</h3>
    </div>
</a>
<h3>{{ blog.title }}</h3>
<p>{{ blog.content }}</p>
</body>
</html>
blog_detail

3、建立url訪問路徑

修改全域性的myblog下的urls.py

"""myblog URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from blog.views import blog_list

urlpatterns = [
    path('', blog_list, name='home'),  # 主頁路徑
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),  # 部落格app路徑
]
myblog_urls.py

在blog app下建立url路徑,新建urls.py

from django.urls import path
from . import views
urlpatterns = [
    path('<int:blog_pk>',views.blog_detail,name='blog_detail')
]
blog_urls.py

4、啟動服務,執行測試

此時我們在瀏覽器輸入:http://127.0.0.1:8000/

點選myBlog,跳轉到詳情:

 

 如果沒有資料的話,我們可以進入admin後臺管理系統建立。

 

 然後重新整理首頁:

 

 就出現了剛才建立的部落格!