带变量的Django URL正则表达式 [英] Django URL regex with variables

查看:164
本文介绍了带变量的Django URL正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望有人可以以此指向我正确的方向。我几乎尝试了所有我能想到的东西,但似乎无法使它正常工作。我有一组要在Django中匹配的URL:

Was hoping someone could point me in the right direction with this. I've tried nearly everything I can think of, but I can't seem to get it to work. I've got a set of URLs I'd like to match in Django:

www.something.com/django/tabs/

www .something.com / django / tabs /?id = 1

www.something.com/django/tabs/
www.something.com/django/tabs/?id=1

基本上,我想做到这一点,以便您只需访问www.something.com/django/tabs /将您带到初始页面,您可以在其中浏览所有内容。但是,当您访问第二个URL时,它将带您到一个特定的页面,您可以从第一个URL浏览到该页面。基于数据库中的对象呈现此页面,这就是为什么存在ID号的原因。我曾尝试在网址正则表达式中说明这一点,但似乎没有任何效果。他们都把我带到主页。

Basically, I want to make it so that when you just visit www.something.com/django/tabs/ it takes you to a splash page where you can browse through stuff. When you visit the second URL however, it takes you to a specific page which you can browse to from the first URL. This page is rendered based on an object in the database, which is why the id number is there. I've tried to account for this in the URL regex, but nothing I try seems to work. They all just take me to the main page.

这是我在主站点文件夹中的urls.py中拥有的内容:

This is what I have in urls.py within the main site folder:

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^tabs/', include("tabs.urls")),
]

并在urls.py中该应用的文件夹:

and within urls.py in the app's folder:

urlpatterns = [
    url(r'\?id=\d+$', tab),
    url(r'^$', alltabs)
]

有人会友好地指出我正确的方向吗?

Would anyone be so kind as to point me in the right direction? Thanks in advance!

推荐答案

在这里,您没有遵循正确的方法。查询参数用于轻微更改页面的行为。像添加的过滤器,搜索查询等。

You are not following the right approach here. Query paramers are used to change the behaviour of the page slightly. Like a added filter, search query etc.

我建议您只有一个视图,并根据视图中的查询参数呈现不同的模板。

What i would suggest is you have only one view and render different templates based on query parameters in the view.

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^tabs/', alltabs),
]

在您的<在code> alltab 视图中,您可以看到类似的内容。

In your alltab views you can have something like this.

def alltabs(request):
    if request.GET.get("id"):
        id = request.GET.get("id")
        your_object = MyModel.objects.get(id=id)

        return render_to_response("tab.html", {"object":your_object})
    return render_to_response("alltab.html")

希望这会有所帮助

这篇关于带变量的Django URL正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆