一、 安裝PyCharm專業版 注意不要安裝社區版,因爲社區版沒有集成Django框架,得自己安裝配置,過程比較繁瑣
二、 打開PyCharm專業版,新建一個Django項目,項目名稱爲“FirstWebDemo”,應用名稱爲“FirstApp”
1.png
創建完成後,項目的邏輯組織結構爲
2.png
三、在urls.py中添加代碼path(r'mainpage', views.index, name='index'),
這裏mainpage是需要在瀏覽器中輸入的接口名稱,比如http://127.0.0.1:8000/mainpage,
而index則是輸入該網址之後,相應會被調用的接口。當index接口被調用時,根據上一步中的代碼,index.html就會被加載。此時用戶就會看到index.html的內容。
注意,如果是網站主頁的話,可以寫爲path(r'', views.index, name='index'),這裏將接口名稱置空,表示在瀏覽器輸入http://127.0.0.1:8080,就會調用index接口,從而加載index.html頁面。
url.py中的完整代碼爲
from django.contrib import admin from django.urls import path from FirstApp import views urlpatterns = [ path('admin/', admin.site.urls), path(r'mainpage', views.index, name='index') ]
四、在views.py中添加index接口
from django.shortcuts import render # Create your views here. def index(request): return render(request, 'index.html')
五、在templates下新建index.html文件,內容爲
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>測試</title> </head> <body> This is my first page. </body> </html>
六、打開瀏覽器,輸入http://127.0.0.1:8000/mainpage
3.png