from django.contrib import admin
from django.urls import path
from learn import views as learn_views
urlpatterns = [path('', learn_views.index),
path('admin/', admin.site.urls)]
上述步骤完成之后,执行以下命令
python manage.py runserver
结果如下
Performing system checks...
System check identified no issues (0 silenced).
You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
July 03, 2018 - 16:39:12
Django version 2.0.4, using settings 'Test.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Hello World!
四、在网页上做加减法
1、采用/add/?a=4&b=5这样get方法进行
django-admin.py startproject zqxt_views
cd zqxt_views
python manage.py startapp calc
修改calc/views.py文件
from django.shortcuts import render
from django.http import HttpResponse
def add(request):
a = request.GET['a']
b = request.GET['b']
c = int(a) + int(b)
return HttpResponse(src(c))
request.GET 类似于一个字典,更好的办法是用 request.GET.get('a', 0) 当没有传递 a 的时候默认 a 为 0
接着修改zqxt_view/urls.py文件,添加一个网址来对应我们新建的视图函数。
from django.contrib import admin
from django.urls import path
from calc import views as calc_views
urlpatterns = [path('add/', calc_views.add, name='add'),
path('admin/'), admin.site.urls]
打开服务器并访问,
python manage.py runserver 8002
结果如下
Performing system checks...
System check identified no issues (0 silenced).
You have 14 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, contenttypes, sessions.
Run 'python manage.py migrate' to apply them.
July 03, 2018 - 17:13:58
Django version 2.0.4, using settings 'zqxt_views.settings'
Starting development server at http://127.0.0.1:8002/
Quit the server with CTRL-BREAK.
2、采用/add/3/4的网址形式
修改calc/views/py 文件,定义一个新函数
def add2(request, a, b):
c = int(a) + int(b)
return HttpResponse(str(c))
然后在urls.py文件中添加一个新的url
path('add/<int:a>/<int:b>/', calc_views.add2, name = 'add2')
五、URL name详解
1、打开zqxt_views/urls.py
from django.conf.urls import url
from django.contrib import admin
from calc import views as calc_views
urlpatterns = [
path('add/<int:a>/<int:b>/', calc_views.add2, name= 'add2'),
path('add/', calc_views.add, name='add'),
path('admin/', admin.site.urls),
]