其他分享
首页 > 其他分享> > 【django学习-03】URLS(路由系统)

【django学习-03】URLS(路由系统)

作者:互联网

#urls.py
re_path('mydata/([0-9]{4})/([0-9]{2})',views.myData),     #视图函数需要传入两个形参接收这里()起来的内容,无命名

#views.py
def myData(req,y,m):
    return HttpResponse("year"+ y+"month"+m)
- 1.2:有命名
#urls.py
re_path('mydata_name/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})',views.myData_name),     #视图函数需要传入两个参接收这里正则提取的内容,有命名

#views.py
def myData_name(req,year,month):
    return HttpResponse("year"+ year+"month"+month)
#urls.py
re_path('mydata_name1/(?P<year>[0-9]{4})/(?P<month>[0-9]{2})',views.myData_name1,{"name":"xwl"}),

#views.py
def myData_name1(req,year,month,name):
    return HttpResponse("year"+ year+"month"+month+name)
#urls.py
re_path('login',views.login,name="xwl"),

#views.py
def login(req):
    if req.method == "POST":
        username = req.POST.get("username")
        pwd = req.POST.get("pwd")
        if username == "xwl" and pwd == "123":
            return HttpResponse("登录成功!!!")

    return render(req,"login.html")

#templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
{#<form action="/login" method="post">#}
<form action="{% url "xwl" %}" method="post">
{#    使用别名#}
    <input type="text" name="username">
    <input type="password" name="pwd">
    <input type="submit" value="submit">
</form>

</body>
</html>
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
- 4、blog/urls.py配置即可
#mysite828/urls.py
from django.contrib import admin
from django.urls import path,re_path,include
from blog import views

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

#views.py
def include_ces(req):
    return HttpResponse("include")

#blog/urls.py
from django.urls import path,re_path,include
from blog import views

urlpatterns = [
    re_path('include/', views.include_ces),

]

标签:03,URLS,views,py,视图,django,urls,path,include
来源: https://www.cnblogs.com/xwltest/p/16641113.html