您现在的位置是: 网站首页 >Django Django
Django的reverse和reverse_lazy跳转链接
admin2018年12月19日 16:21
【Django
】
1835人已围观
# Django的reverse和reverse_lazy 现在定义了一个 url ```python urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), ] ``` 当然了,如果我想在 template 里使用的话可以如下 ```html <h1>{% url 'index' %}</h1> ``` 现在后端有下面这段代码 ```python from django.core.urlresolvers import reverse class UserProfileView(FormView): template_name = 'profile.html' form_class = UserProfileForm success_url = reverse('index') ``` 如果运行,会报如下错 ```python django.core.exceptions.ImproperlyConfigured: The included urlconf 'config.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. ``` ## 方法一 ```python from django.core.urlresolvers import reverse_lazy class UserProfileView(FormView): template_name = 'profile.html' form_class = UserProfileForm success_url = reverse_lazy('index') # use reverse_lazy instead of reverse ``` ## 方法二 ```python from django.core.urlresolvers import reverse class UserProfileView(FormView): template_name = 'profile.html' form_class = UserProfileForm def get_success_url(self): # override this function if you want to use reverse return reverse('index') ``` 单单从代码上看,`reverse_lazy`要方便很多。根据 https://docs.djangoproject.com/en/1.11/ref/urlresolvers/#reverse-lazy 上的描述,`reverse_lazy`当项目里的URLConf未加载时用来取代`reverse`。 ## reverse_lazy可以用在以下几个场景 * 在 class-based view 中用 reversed url. (上述方法一) * 装饰器中使用 reversed url (例如装饰器 `django.contrib.auth.decorators.permission_required()` 中 `login_ur`l 参数) * 函数参数的默认值中的 reversed url 最后看了下两者的源码,看的一知半解,但是如下源码中 ```python # reverse def reverse(viewname, urlconf=None, args=None, kwargs=None, prefix=None, current_app=None): ...... ``` ```python # reverse_lazy reverse_lazy = lazy(reverse, six.text_type) ``` 可以看到`reverse_lazy`是`reverse`的一层封装,这样我就可以用`reverse_lazy`可以用在任何`reverse`的场景里,而且不用担心出错。 ## 新版reverse_lazy引用 ```python from django.urls import reverse_lazy ``` ## reverse_lazy带参数跳转 实例 ```python def get_success_url(self): phase_id = self.request.GET.get('phase_id') # print(phase_id) if phase_id: return reverse_lazy('casual:works_list_by_phase', kwargs={'phase_id': phase_id}) else: return reverse('casual:works_list') ```
很赞哦! (0)
相关文章
文章交流
- emoji
当前用户
未登录,点击 登录猜你喜欢
获取logging日志的大小,将原文件重命名
-
【K8s+Docker技术全解】10.Master主控节点服务-部署kube-scheduler、检查集群状态
-
【Django在线教育平台】02.创建该项目用到的数据库模型类
-
【Vue+DRF生鲜电商】06.DRF环境配置,使用Serializer类序列化商品列表
-
【telnetlib】使用Python登录Cisco交换机执行命令
-
【gnirehtet、adb】安卓手机通过USB连接到电脑上网
-
【Flask微电影】23.基于角色访问控制-管理员管理和访问权限控制
-
腾讯云主机每天早上内存暴涨引发CPU满载问题
-
pycrypto安装报错error:Unable to find vcvarsall.bat



GitHub
QQ
StarMeow