建立首頁

      在〈建立首頁〉中尚無留言

撰寫網頁

現在已經可以在Pycharm開始撰寫網頁了。首先在專案名稱按右鍵,new/Python file,輸入index.py,然後輸入如下代碼

from django.http import HttpResponse
def html(request):
    s= '''
        <html>
            <head>
                <title>測試</title>
            </head>
            <body>
                <table border="1" cellpadding="0" cellspacing="0">
                    <tr>
                        <td>第一格</td>
                        <td>第二格</td>
                        <td>第三格</td>
                    </tr>
                    <tr>
                        <td>第四格</td>
                        <td colspan="2">第五格</td>
                    </tr>
                </table>
            </body>
        </html>
''' return HttpResponse(s)

HttpResponse這個方法的用途,就是將字串傳送給客戶端瀏覽器,所以字串必需是 html的格式。

安裝app

開啟 pyweb 目錄下的設定檔settings.py,在 “INSTALLED_APPS” 下新增 “index”,此即表示 index.py為一支 app

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'index',
]

設定網址連結

網址連結是在設定某個網址要連結到某個 .py 檔裏的某個函數,設定檔為 pyweb/urls.py。請在 urls.py 檔案新增底下藍色的代碼. path(”, index.html) 其中的 ” 空字串, 表示在網址後並不指名任何檔名. 如 http://mahaljsp.asuscomm.com:7000/(空白, 沒任何檔名)

from django.contrib import admin
from django.urls import path
import index
urlpatterns = [
    path('admin/', admin.site.urls),
    path('', index.html),
]

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *