Django-argument
程序员文章站
2022-06-15 22:24:11
...
给url 添加参数
1 创建文件:
2 . 在myApp 文件里新建一个urls.py 文件
配置myApp 里的views.py 文件 和 urls.py 文件
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def just_test_one(request):
myId = request.GET.get('id', '0')
name = request.GET.get('name', 'zhangsan')
return HttpResponse('name=%s, id=%s' %(name, myId))
配置urls 文件
from django.conf.urls import url
from . import views
urlpatterns = [
url('just_test_one', views.just_test_one)
]
3 配置 myAru里的urls.py文件
from django.contrib import admin
from django.urls import path
from django.conf.urls import include
urlpatterns = [
path('admin/', admin.site.urls),
path('index/', include('myApp.urls'))
]
5 启动服务器,进入指定url ,如下图所示
我们还可以对myApp里的urls 文件进行修改,进而改变url
代码如下
views.py 文件
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def just_test_one(request):
myId = request.GET.get('id', '0')
name = request.GET.get('name', 'zhangsan')
return HttpResponse('name=%s, id=%s' %(name, myId))
def second(request, mid, name):
return HttpResponse('id=%s, name=%s' % (mid, name))
def third(request, a, b, name):
c = int(a) + int(a)
return HttpResponse('sum=%s, name=%s' %(c, name))
urls.py 文件
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'just_test_one', views.just_test_one),
# http://localhost:8000/index/second/100/hello
url(r'second/(\d+)/(\w+)', views.second),
# ?P<参数>
url(r'third/(?P<a>\d+)/(?P<b>\d+)/(?P<name>\w+)', views.third)
]
最后运行,输入不同的网址,可以看到second 和third 的不同
推荐阅读