Django 教程 1 – 入门, 安装,建立简单网页应用 | Django tutorial 1 – getting start, install and building a simple webapp

用pip安装Django

pip install django

建立一个叫“demo”的新project

django-admin startproject demo

把web server跑起来

cd demo
python manage.py runserver

然后打开点开 http://127.0.0.1:8000,应该能看到以下页面,说明建立成功了

如果不想用默认的8000,想换一个端口(port),比如1234,可以这样启动
python manage.py runserver 1234

建立一个叫“myapp“的app

python manage.py startapp myapp

这个时候,demo目录下的内容如下

编辑myapp下面的views.py

from django.shortcuts import render
from django.http import HttpResponse

# Create your views here.
def index(response):
    return HttpResponse("<h1>Hello from my first Django app</h1>")

在myapp下面新建一个叫 urls.py 的文件

myapp/urls.py 写入如下内容

from django.urls import path
from . import views

urlpatterns = [
    path("", views.index, name="index"),
]

注意 urlpatterns 变量名一定不能写错,否则会出现以下错误

django.core.exceptions.ImproperlyConfigured: The included URLconf '<module 'myapp.urls' from '/<project path>/demo/myapp/urls.py'>' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import.

打开demo/urls.py

demo/urls.py 修改为如下

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include("myapp.urls")),
]

浏览器里刷新 django 网页

到这里,我们就用Django做好一个能用的web app了。这里每个网页views.py里面用HttpResponse输出html,这肯定是不scalable。而且这样很能加入javascript/css。解决办事是我们需要html template。下一片文章将会介绍在Django html template。

Leave a Comment

Your email address will not be published.