django-URL实例命名空间(十一)

时间:2022-07-23
本文章向大家介绍django-URL实例命名空间(十一),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

每生成一个地址,都是一个实例。使用实例命名空间,针对于一个app而言。

book/views.py

from django.http import HttpResponse
from django.shortcuts import render,redirect,reverse
from django.urls import resolve

# Create your views here.
def index(request):
    username = request.GET.get("username")
    if username is not None:
        return HttpResponse("welcome!")
    else:
        path=request.path
        current_namespace=resolve(path).namespace
        return redirect(reverse('{}:loose'.format(current_namespace),kwargs={'a':100,'b':200}))

def error(request,a,b):
    sum=a+b
    return HttpResponse("<h1>path:{}</h1>".format(request.path))

book/urls.py

from django.urls import path
from . import views
app_name ="book"
urlpatterns = [
    path('', views.index,name='index'),
    path('error/<int:a>/<int:b>', views.error,name='loose'),
]

主urls.py

from django.contrib import admin
from django.urls import path,include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('book/',include('book.urls',namespace="book")),
    path('page/',include('book.urls',namespace="page")),
]