Wei-Ting
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    --- tags: python --- # DAY 25 Django建置其他網頁 ## 模板的繼承 我們可以編寫一個含有通用元素的基底模板,而不要直接在每個頁面中重複寫入這些通用元素 ### 父模板 我們會建立一個base.html並存在跟index.html同一個資料夾內,這個檔案會有所有頁面都需要的通用元素,其他模板也都繼承自base.html,如下 ```html= <p> <a href="{% url 'learning_logs:index' %}">Learning Log</a> </p> {% block content %}{% endblock %} ``` 上面程式碼第二行{% url 'learning_logs:index' %}會生成一個URL,此URL與learning_logs/urls.py中定義名為index的URL模式比對符合,在第五行插入一對block標記,此區塊名稱叫content,是個佔位用的符號,含有的資訊會椅子模板定義 ### 子模板 現在我們需要重新編寫index.html檔讓他繼承自base.html,如下 ```html= {% extends "learning_logs/base.html" %} {% block content %} <p>hello,this is weiting's learning_log</p> {% endblock content %} ``` 上面程式碼第一行是在說子模板第一行要有{% extends %}標記,讓Django知道是繼承哪個父模板,第三行插入{% block %}標記來定義content區塊,是將我們在learning log的文字段落插入至content ## 主題&個別主題的頁面 ### URL模式 首先要來修改learning_logs資料夾裡的urls.py檔,如下 ```python= from django.conf.urls import url from django.urls import path from . import views app_name='learning_logs' urlpatterns=[ path('',views.index,name='index'), # 顯示所有主題 path('topics/',views.topics,name='topics'), # 顯示個別主題 path('<int:topic_id>/',views.topic,name='topic'), ] ``` 上面程式碼第九行我們在正規表示式中加了topic/字樣,當Django在檢測請求URL時,符合比對的URL請求會被傳到views.py中的topic函式處理 上面程式碼第十二行和第九行不同的地方是多了topic_id,當使用者要看MIIA主題(id 為 1)的詳細內容介面,Django會呼叫topic視圖函式,把存放在topic_id中的值當成引數傳給它,然後依照topic_id的值來取得對應的值 ### 視圖 ```python= from django.shortcuts import render from .models import Topic # 匯入Topic模型 def index(request): return render(request, 'learning_logs/index.html') # 顯示所有主題 def topics(request): topics = Topic.objects.order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) # 顯示個別主題和它的entries def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) ``` 上面程式碼第九行topic()函式需要一個參數,Django從伺服器收到的request物件,第十行是查詢資料庫請求Topic物件,並按照date_added屬性對它們排序,第十一行是定義一個模板傳送到context字典,第十二行是除了request物件和模板路徑之外,還要把context變數給render() 顯示個別主題是從第十五行開始,第十五行除了request物建之外還需要參數的是圖函式,此函式取得topic_id的值再存到topic_id中,第十六行是用get()函式用id來取得指定主題 ### 模板 * 顯示全部主題的模板 顯示所有主題頁面的模板會收到context字典,所以能使用topic()所提供的資料,我們要建立一個topics.html檔,一樣存在跟index.html同一個資料夾中,topics.html程式碼如下 ```html= {% extends "learning_logs/base.html" %} {% block content %} <p>Topics</p> <ul> {% for topic in topics %} <li> <a href="{% url 'learning_logs:topic' topic.id %}">{{ topic }}</a> </li> {% empty %} <li>No topics have been added yet.</li> {% endfor %} </ul> {% endblock content %} ``` 上面程式碼就像index.html模板一樣,會先用{%extends%}繼承base.html,再定義content區塊,第八行的for topic in topics就是遍訪context字典中的topics串列,每個for迴圈都要有像第十四行的{%endfor%},我們主題清單都會有一個連結,第十行的連結就是連結顯示對應特定主題的內容 :arrow_down: Topics連結點進去的畫面如下 ![](https://i.imgur.com/a0kZ2Hk.png) * 顯示個別主題和其內容的模板 ```html= {% extends 'learning_logs/base.html' %} {% block content %} <p>Topic: {{ topic }}</p> <p>Entries:</p> <ul> {% for entry in entries %} <li> <p>{{ entry.date_added|date:'M d, Y H:i' }}</p> <p>{{ entry.text|linebreaks }}</p> </li> {% empty %} <li> There are no entries for this topic yet. </li> {% endfor %} </ul> {% endblock content %} ``` 上面程式碼是我們要再創一個topic.html模板,也是以base.html為基底擴充,第五行是創一個Topic變數來存放context字典,隨後我們定義了顯示項目的清單,第十一行會顯示日期時間,第十二行是確保格式有換行符號的長紀錄項目,且能讓瀏覽器解讀,以免顯示出沒有斷行超出畫面的文字區塊 :arrow_down: 點按MIIA主題時可看到其內容的畫面如下 ![](https://i.imgur.com/3sogccI.png) #### 今天結束,各位明天見 :hand: *** 資料來源:<<python程式設計的樂趣>>-Eric Matthes著/H&C譯

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully