欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Django-argument

程序员文章站 2022-06-15 22:24:11
...

给url 添加参数
1 创建文件:
Django-argument
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))

Django-argument
配置urls 文件

from django.conf.urls import url
from . import views

urlpatterns = [
    url('just_test_one', views.just_test_one)
]

Django-argument
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'))
]

Django-argument

5 启动服务器,进入指定url ,如下图所示
Django-argument

我们还可以对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))

Django-argument
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)
]

Django-argument

最后运行,输入不同的网址,可以看到second 和third 的不同
Django-argument

相关标签: Django argument

推荐阅读