zoukankan      html  css  js  c++  java
  • Django之URL路由

    1.URL配置

    基本格式 :

    HttpResponse # 返回的是字符串
    render #模板渲染 模板就是html页面 渲染就是字符串替换
    
    

    在Django2中:

    from django.contrib import admin
    from django.urls import  path,re_path
    from  app01  import  views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        re_path('^index/', views.index),
    ]
    
    • 正则表达式:一个正则表达式字符串
    • views视图函数:一个可调用对象,通常为一个视图函数或一个指定视图函数路径的字符串

    示例

    urls.py

    from django.contrib import admin
    from django.urls import  path,re_path
    from  app01  import  views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        re_path('^login/',views.login), #路径分发   不区别请求方法
    ]
    

    views.py

    from django.shortcuts import render ,HttpResponse
    
    # Create your views here.
    
    def login(request):
        print('请求方法',request.method)
        if request.method == 'GET':
            return render(request,"login.html")
        else:
            print(request.POST) #{'username': ['zbb'], 'pwd': ['222']}>
            name = request.POST.get("username")
            pwd = request.POST.get("pwd")
            if name == 'zbb' and pwd == '123':
                return HttpResponse("登录成功")
            else:
                return HttpResponse("登录失败")
    
    

    login.html

    # 'django.middleware.csrf.CsrfViewMiddleware', #注释才能接收post
    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <h1>追梦NAN变成了大叔</h1>
    <form action="" method="post">
        用户名:<input type="text" name="username">  
        密码: <input type="text" name="pwd">
        <input type="submit">
    </form>
    
    </body>
    
    </html>
    

    2.正则表达式

    分组命名匹配

    request #request  后面跟着分组正则里面的参数
    

    urls

    from django.contrib import admin
    from django.urls import  path,re_path
    from  app01  import  views
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        re_path('^login/',views.login),
        # 无名分组参数
        re_path('article/(d+)/(d+)/',views.article), #位置传参
        #有名分组参数
        re_path('dd/(?P<xx>d+)/(?P<oo>d+)/',views.dd)
        #是关键字传参
    ]
    

    views

    def article(request,year,moth):
        return  HttpResponse(year+"年"+moth+'月')
    
    def dd(request,xx,oo):
        return  HttpResponse(xx+oo+'月')
    #第一个参数必须是request,后面跟的三个参数是对应着上面分组正则匹配的每个参数的
    

    访问

    http://127.0.0.1:8000/article/1/2/
    http://127.0.0.1:8000/dd/1/2/
    
  • 相关阅读:
    zz--Add-Migration与EF及Mysql的使用。。
    最后学期
    E. Tree Queries 题解(思维+dfs序)
    D. 0-1 MST 题解(补图的联通块)
    F. Equalizing Two Strings 题解(思维)
    CSUST 白银御行想展示 题解(思维)
    E2. Rubik's Cube Coloring (hard version) 题解(dp+思维)
    D. Hemose in ICPC ? 题解(二分+dfs序+交互)
    C. Bakry and Partitioning 题解(思维+两次dfs)
    E. Bored Bakry 题解(二进制+思维)
  • 原文地址:https://www.cnblogs.com/zdqc/p/11585260.html
Copyright © 2011-2022 走看看