viewname可以是url模式的名字,也可以是name所指的名字,
urlconf这个属性决定当前的反向解析使用哪一个URLconf模块,默认是URLconf
args用于传递参数,可以是元组或者列表,顺序填充URL中的位置参数
kwargs和args一样,但传递的是字典类型,使用关键字指定参数和参数值。注意args和kwargs不可同时出现
current_app当前执行的视图是哪一个应用的
re_path(‘msg/(?P<name>[\u4e00-\u9fa5]{0,4})/(?P<year>[0-9]{4})/(?P<month>0[0-9]|1[0-2])/(?P<day>0[1-9]|1[0-9]|2[0-9]|30)/‘,views.time_time,name=‘time‘),#指定url的name
在shell环境中
>>> from django.urls import reverse >>> reverse(‘time‘,args=(‘诺言‘,2019,11,20)) ‘/firstapp/msg/%E8%AF%BA%E8%A8%80/2019/11/20 >>> reverse(‘time‘,kwargs={‘name‘:‘诺言‘,‘year‘:2019,‘month‘:11,‘day‘:20}) ‘/firstapp/msg/%E8%AF%BA%E8%A8%80/2019/11/20/‘
reverse常常用于视图重定向,reverse中的viewname也可以传递视图对象
from django.urls import reverse from django.http import HttpResponseRedirect def test(request,ceshi): return HttpResponseRedirect(reverse(‘time‘,kwargs={‘name‘:‘诺言‘,‘year‘:2019,‘month‘:11,‘day‘:20}))
URL命名空间分为两部分 1、app_name:正在部署的应用, 2、区分同一个应用部署的多个不同空间
首先在总项目的urls.py中增加命名空间
urlpatterns = [ path(‘admin/‘, admin.site.urls), path(‘firstapp/‘,include(‘firstApp.urls‘,namespace=‘first‘)) ]
在应用中添加
app_name=‘first‘
最后修改一下reverse方法
from django.urls import reverse from django.http import HttpResponseRedirect def test(request,ceshi): return HttpResponseRedirect(reverse(‘first:time‘, kwargs={‘name‘:‘诺言‘,‘year‘:2019,‘month‘:11,‘day‘:20}, current_app=request.resolver_match.namespace))
重定向分为两种:临时重定向和永久重定向
原文:https://www.cnblogs.com/xymaxbf/p/11964208.html