【问题标题】:Python, Django 1.7 : Redirect all URLs to a single controllerPython,Django 1.7:将所有 URL 重定向到单个控制器
【发布时间】:2015-05-02 22:34:37
【问题描述】:

我们的基本网址是so.com 因此,如果 URL 以 abc 开头,例如

so.com/abc/
so.com/abc/123
so.com/abc?newtab=123
so.com/abc#123
so.com/abc/123?tab=new
...

那么所有这些 URL 模式都应该转到 Class Abc

myapp/urls.py 
...
url(r'^abc[a-zA-Z0-9=#_\?\-/]+$',views.Abc.as_view(),name='abc')

myapp/myviews/abc.py

class Abc(View):
   def get(self,request):
    ...
   def foo(user_id):
   ...
   def bar(post_id):
   ...

在函数get(self,request): 中如何获取请求的 abc 之后的所有内容。 例如

so.com/abc/xyz => /xyz
so.com/abc#123 => 123
so.com/abc?tab=new => ?tab=new 
 so.com/abc/123?tab=new => tab = new and 123 

#123 加在 abc 之后会自动转换成abc/#123

如何完成这项工作?

我看过很多问题,但都没有帮助。

Django Get Absolute URL

What is a "slug" in Django?

How to get the current URL within a Django template?

...

【问题讨论】:

    标签: python regex django url model-view-controller


    【解决方案1】:

    所以,首先,你不能得到#参数。那个不是发送到服务器的,阅读更多here

    解析so.com/abc/xyz => /xyzso.com/abc?tab=new => ?tab=new

    url(r'^abc/?$',views.Abc.as_view(),name='abc')
    url(r'^abc/(?P<param>\w+)/?$',views.Abc.as_view(),name='abc')
    
    class Abc(View):
    
        def get(self,request,param=None):
            print param # in param you get /xyz
            tab = request.GET["tab"] # here you get ?tab=new 
    

    【讨论】:

    • 你检查了吗?在我的系统上 so.com/abc/xyz 打印无。
    • 它仍然给出 None 。
    • 这种情况下 url so.com/abc/ 无法解析。
    • @sonukumar 是的,只需添加/?
    • 它仍然错了你有可选的` (?P\w+)` 所以你必须在这之后添加?
    猜你喜欢
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2016-03-06
    • 1970-01-01
    相关资源
    最近更新 更多