「Django筆記」修訂間的差異
跳至導覽
跳至搜尋
Tankianting(討論 | 貢獻) |
Tankianting(討論 | 貢獻) |
||
行 28: | 行 28: | ||
<pre> | <pre> | ||
from django.http import Http404, HttpResponse | from django.http import Http404, HttpResponse | ||
import json | |||
from . import config # import the config variables in the file './config.py'. | from . import config # import the config variables in the file './config.py'. | ||
於 2022年6月3日 (五) 04:39 的修訂
建立新專案
django-admin startproject [網站目錄名]
跑伺服器
cd [網站目錄名]; ./manage.py runserver [Port number]
子結構說明
- urls.py - url 網頁路徑傳送門
- views.py - 顯示的方式
urls.py 基礎
假設urls.py 的所屬目錄包含 views.py,views.py有user這個函數,我們要傳字串/user/abc 的 abc 當成 user 函數的 username 變數,則可以這樣設定:
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('/users/<slug:username>', views.user), path('admin/', admin.site.urls), ]
view.py
假設要做 activitypub 協定,回傳 json 的話,可以這樣設定:
from django.http import Http404, HttpResponse import json from . import config # import the config variables in the file './config.py'. def user(request, username): user_json = {"@context": "https://www.w3.org/ns/activitystreams", "id": config.site_url + "/users/" + username, "inbox": config.site_url + "/users/" + username + "/inbox", "outbox": config.site_url + "/users/" + username + "/outbox", "type": "Person", # the json for the type "name": username , # user name } if username != 'John': raise Http404() # throw 404 else: # return json file with setting content_type return HttpResponse(json.dumps(user_json), content_type="application/activity+json")
如果不是 John,就回傳 Http404()。