django学习之reverse方法

reverse翻译就是“反转”的意思,反解析url以直接访问其它视图方法。它一般以下面的形式出现:

from django.core.urlresolvers import reverse
def reverse(self, lookup_view, *args, **kwargs):
    return self._reverse_with_prefix(lookup_view, '', *args, **kwargs)


它有点类似django里模板语言,比如:

<a class="buton" href="{% url forum.views.forum forum.pk %}">VIEW</a>


好,那就说说reverser的用法:它有三个参数,loopup_view不用说是要执行动作的路径,args是固定参数,kwargs是动态参数。如:

return HttpResponseRedirect(reverse("forum.views.forum",args=[pk],kwargs={'body':"email body"}))
print reverse('userGroupList')  #会输出一个url


reverser也有一个用处,那就是django的一条哲学是(don't repeat yourself DRY ):http://xiaolin0199.iteye.com/blog/585470

如果未来某天我们的url发生了改变,使用这种办法我们就可以不用修改多出的url链接了。

出处:http://xiaolin0199.iteye.com/blog/585470

可能出现的问题:

 1.如果存在无效的url配置(url对应的函数删除了等),会提示错误

 2.注意添加好reverse的函数的路径,否则会出现:

return HttpResponseRedirect(reverse('agentList'))

Reverse for 'xxx' with arguments '()' and keyword arguments '{}' not found.

修改为:

return HttpResponseRedirect(reverse('pms.agent.index.agentList'))

ok!

原文地址:https://www.cnblogs.com/chenjianhong/p/4144836.html