「Django筆記」修訂間的差異
跳至導覽
跳至搜尋
Tankianting(討論 | 貢獻) |
Tankianting(討論 | 貢獻) |
||
行 21: | 行 21: | ||
] | ] | ||
</pre> | </pre> | ||
==view.py== | |||
假設要做 activitypub 協定,回傳 json 的話,可以這樣設定: | |||
<pre> | |||
from django.http import Http404, JsonResponse | |||
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 JsonResponse(user_json) | |||
</pre> | |||
如果不是 John,就回傳 Http404()。 | |||
==參考== | |||
* https://docs.djangoproject.com | |||
* http://stackflow.com |
於 2022年6月3日 (五) 04:34 的修訂
建立新專案
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, JsonResponse 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 JsonResponse(user_json)
如果不是 John,就回傳 Http404()。