简体   繁体   English

如何在Django中创建类似controller / action / id的url模式?

[英]How do I create a url pattern like controller/action/id in django?

I'm trying to create a url pattern that will behave like controller/action/id route in rails. 我正在尝试创建一个URL模式,其行为将类似于Rails中的controller / action / id路由。 So far here is what I have : 到目前为止,这是我所拥有的:

from django.conf.urls.defaults import *
import views

urlpatterns = ('',
              (r'^(?P<app>\w+)/(?P<view>\w+)/$', views.select_view),
              )

Here is my 'views.py': 这是我的“ views.py”:

def select_view(request, app, view):
    return globals()['%s.%s', % (app, view,)]()

So far this hasn't worked. 到目前为止,这没有用。 I get a key error exception in the 'globals' function. 我在'globals'函数中收到一个关键错误异常。 Am I going in the right direction here? 我在这里朝正确的方向前进吗?

Try something like this: 尝试这样的事情:

from django.utils.importlib import import_module

def select_view(request, app, view):
    mod = import_module('%s.views' % app)
    return getattr(mod, view)(request)

It is obviously oversimplified example, what you do is import views.py from your app and see if it has view function, and if it does execute that function giving request as the first argument. 显然,这是一个过于简化的示例,您要做的是从应用程序中导入views.py ,并查看它是否具有view功能,以及是否确实执行了该功能,并以请求作为第一个参数。

See some examples of how Django does it with get_callable and autodiscover methods. 查看有关Django如何使用get_callableautodiscover方法进行操作的get_callable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM