【问题标题】:Django: Get relative uri from views.pyDjango:从views.py获取相对uri
【发布时间】:2014-09-04 21:38:01
【问题描述】:

这是我目前拥有的:

urls.py:

 ...
url(r'this/is/relative', 'myapp.views.callview', name='myapp_callview'),
...

views.py:

def callview(request, **kwargs):

    # I can get the complete url by doing this
    print request.build.absolute_uri() # Prints: https://domain:8080/myapp/this/is/relative

    # How do I just get: /myapp/this/is/relative or even /this/is/relative

我想从视图中提取相对 uri。我可以只使用正则表达式,但我认为已经有一些东西可以让我这样做。

【问题讨论】:

  • 出于好奇,您希望通过获取相对 url 来提取什么?如果您想在 URL 结构中捕获参数,您可以在 URL 中包含这些参数,以便将它们传递给方法。
  • @KevinLondon:我只是想获取相对 url 而不是任何参数。
  • 可能会在视图中使用一些简单的东西,例如:print(str(request.build_absolute_uri()).split(request.META.get('HTTP_HOST'))[1])

标签: django


【解决方案1】:

这会给你"/myapp/this/is/relative":

from django.core import urlresolvers
relative_uri = urlresolvers.reverse("myapp_callview")

链接到 Django 文档页面:https://docs.djangoproject.com/en/dev/ref/urlresolvers/

【讨论】:

    猜你喜欢
    • 2014-03-30
    • 2018-04-16
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-04-03
    • 2018-05-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多