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 28 Django允許使用者擁有自己的資料 使用者應該要能輸入他們自己的資料,因此我們建置一個系統確定哪些資料屬於哪個使用者所有,然後限制某些頁面的存取權,以便讓使用者輸入自己的資料 ## 限制存取 Django提供了@login_required修飾模式來讓我們輕鬆實現這個目標 * 對Topics頁面的存取 每個主題都是由使用者所建立擁有的,因此只有登入的使用者才能夠請求主題頁面,我們要打開learning_logs資料夾中的views.py來匯入login_required函式,再將login_required函式當作修飾模式用在topics視圖函式,如下 ```python= --省略-- from django.contrib.auth.decorators import login_required --省略-- @login_required # 會檢測使用者是否已經登入,若已登入才會執行topics()的程式 def topics(request): topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) ``` 要做到重新導向到登入頁面,我們還得在setting.py的尾端新增以下程式碼 ```python= # my settings LOGIN_URL='/users/login' ``` 新增完後我們可以開啟我們的網頁來測試看看是不是登出後就沒辦法點進去Topics裡 * 對整個learning log 頁面進行存取 在learning log專案中我們要對主頁、登入註冊頁面和登出頁面是不設限制的,但對其他都要設定存取權,所以我們要在learning logs資料夾中的views.py將@login_required套用到index()以外的每個視圖,如下 ```python= @login_required def topics(request): --省略-- @login_required def topic(request, topic_id): --省略-- @login_required def new_topic(request): --省略-- @login_required def new_entry(request, topic_id): --省略-- @login_required def edit_entry(request, entry_id): --省略-- ``` ## 把資料連接到特定使用者 現在我們要把資料連接到提交他們的使用者上,我們只需要把最高級層的資料連接到使用者,這樣低級層的資料就會跟著連接到所屬的使用者 ### 修改Topic模型 我們要來修改Topic模型,在其中新增一個外部鍵連接使用者,隨後我們會修改遷移資料庫,最後還必須對視圖做一些修改,讓它們只顯示與目前登入使用者相關有連接的資料,我們要開啟models.py來新增一些程式碼,如下 ```python= from django.db import models from django.contrib.auth.models import User # 新增區塊 class Topic(models.Model): --省略-- owner=models.ForeignKey(User,on_delete=models.CASCADE) # 新增區塊 --省略-- ``` ### 遷移資料庫 我們從執行```python manage.py makemigrations learning_logs```命令後,Django會給我們兩個選擇,馬上提供預設值,或是退出並在models.py中新增預設值,在這裡我們選了第一種,因此Django讓我們輸入預設值,為了要把所有現有的主題與原本管理者weiting2關聯起來,我們在這裡輸入1的使用者ID,如下 ![](https://i.imgur.com/y98eWmy.png) 現在我們可以進行遷移了,我們要在虛擬環境下輸入```python manage.py migrate```,如下 ![](https://i.imgur.com/B8vLrj0.png) ## 限制只能存取屬於自己的主題 目前不管以哪個身分登入,都能看到所有主題,我們要來修改成限制存取屬於自己的主題,打開views.py對topics函式新增程式碼,如下 ```python= @login_required def topics(request): topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) ``` 當使用者登入後,request物件會有個user屬性,此屬性儲存了關於該使用者的資訊,Topic.objects.filter(owner=request.user)這段程式碼會讓Django只從資料庫中取得其owner屬性為目前使用者的Topic物件 ## 保護使用者的主題 我們還沒真的限制存取主題頁面,所以任何已登入的使用者都可輸入類似像http://localhost:8000/topics/1 這樣的URL來存取對應的主題頁面,為了修改這樣的問題,我們在topics()視圖函式取得請求的紀錄項目之前先執行檢測,如下 ```python= --省略-- from django.http import HttpResponseRedirect,Http404 --省略-- @login_required def topic(request, topic_id): """Show a single topic, and all its entries.""" topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: # 請求主題與現在使用者不符合 raise Http404 # 返回錯誤頁面 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) ``` ## 保護edit_entry頁面 edit_entry頁面的URL格式為 http://localhost:8000/edit_entry/entry_id ,其中entry_id是個數字,讓我們來保護這個頁面,這樣任何人都不能以這個URL來存他人的紀錄項目,如下 ```python= @login_required def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic if topic.owner != request.user: raise Http404 --省略-- ``` ## 把新主題關連到目前使用者 目前我們新增主題頁面是有問題的,因為它還不會把新主題與任何特定使用者關聯起來,我們可以試著新增主題,會看到一個IntegrityError錯誤訊息,指出learning_logs_topic.user_id不能是NULL,因此我們可以透過request物件存取目前使用者,開啟views.py加入以下程式碼 ```python= @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(request.POST) if form.is_valid(): new_topic = form.save(commit=False) # 新增區塊 new_topic.owner = request.user # 新增區塊 new_topic.save() # 新增區塊 return HttpResponseRedirect(reverse('learning_logs:topics')) --省略-- ``` 第八行的地方我們是先呼叫form.save()並把commit=False當引數傳入,這是因為我們先修改新主題,再把它儲存進資料庫,隨後把新主題的OWNER屬性設為目前使用者,最後對剛定義的主題實例呼叫save() #### 今天結束,各位明天見 :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