侧边栏壁纸
  • 累计撰写 17 篇文章
  • 累计创建 10 个标签
  • 累计收到 0 条评论

目 录CONTENT

文章目录

Django路由

十点差三分
2024-10-13 / 0 评论 / 0 点赞 / 10 阅读 / 0 字

一、传统路由

urls.py

urlpatterns = [
    path('index/',views.index)
]

views.py

def index(request):
    try:
        obj_stu = Student.objects.all().values()
        students = list(obj_stu)
        return JsonResponse({'code': 1, 'data': students})
    except Exception as e:
        return JsonResponse({'code': 0, 'meg': '获取学生信息出现异常,具体错误:' + str(e)})

二、正则路由

urlpatterns = [
    path('api/',include("apps.api.urls")),
    path('web/',include("apps.web.urls")),
]

三、路由分发(多app)

urlpatterns = [
    path('api/',include("apps.api.urls")),
    path('web/',include("apps.web.urls")),
]

四、手动路由分发(单个app)

urlpatterns = [
    path('user/add/',views.user_add),
    path('user/delete/',views.user_delete),
    path('user/updata/',views.user_updata),
    path('user/list/',views.user_list),

    path('user/',([
                     path('add/',views.user_add),
                     path('delete/',views.user_add),
                     path('updata/',views.user_updata),
                     path('list/',views.user_list),
                 ],None,None)),

]

路由分发的本质

  • URL对应函数
 path('user/add/',views.user_add),
  • URL对应元组

    path('user/add/',(元素,appnameh元素,namespance元素)),
    
    path('api/',include("apps.api.urls")),
    
    path('user/add',([],None,None)),
    
urlpatterns = [
    path('user/add/',views.user_add),
    path('user/delete/',views.user_delete),
    path('user/updata/',views.user_updata),
    path('user/list/',views.user_list),

    path('user/',([
                     path('add/',views.user_add),
                     path('delete/',views.user_add),
                     path('updata/',views.user_updata),
                     path('list/',views.user_list),
                 ],None,None)),
    path('user', include(([
                             path('add/',views.user_add),
                             path('delete/',views.user_add),
                             path('updata/',views.user_updata),
                             path('list/',views.user_list),
                    ],None))),

]

路由name

给路由起名字

urlpatterns = [
    path('login/',views.login,name = "v1"),
    path('auth/',views.auth, name = "v2")
]

视图函数中

url = reverse("v2") #/auth/

HTML中

<a href = "/xxx/xxx/xx/">添加</a>
```html
<a href = "{% url 'v2' %}">添加</a>
0

评论区