Django URLS,使用?在URL中 [英] Django URLS, using a ? in the URL

查看:209
本文介绍了Django URLS,使用?在URL中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试一些Django网址匹配。



我想要几个网址,我有一个 http://mysite.com/base?sort=type1/ http://mysite.com/base?sort=type2/ 等。



我不知道如何URL匹配这些表达式:我对Django非常新鲜,从未使用过Reg Ex。



我在基础应用程序中的urls.py有什么:

  url(r'^ $','base.views.main,name ='main'),

我无法弄清楚将我的网址与问号相符。



我正在尝试像

  url(r'^?sort = popular / $' 'base.views.main_popular',name ='main_popular'),

感谢您的帮助! p>

解决方案

?不会匹配?在url里面,它有自己的意思,你可以在这里查看:

Python正则表达式
如果要匹配?的确切字符在你的url里面,你必须以某种方式逃避它(因为它在RegExs中有一个意义),所以你可能想用\(一个反斜杠)
来逃避它,所以你会写\?排序...



编辑:

好​​的,你在评论中说过,似乎这是你的问题, main?sort当您使用 GET / main / 的模板时,会在您的网址模式中发生=流行 $ c>方法字典参数 sort = popular ,只需编写一个区分 GET POST ,在 GET 部分中,像 sort_by = request.GET.get('sort' ''),然后按sort_by变量的值进行排序,将像:

  def main_handler(request):
如果request.method ==POST:
whatever ...
如果request.method ==GET:
sort_by =请求。 GET.get('sort','')
如果sort_by:
按什么排序指向
返回排序的模板
返回render_to_response(该页面及其参数)
/ pre>

放弃那个?在url模式的内部,当您请求具有GET参数的页面时,该模式将被添加。


I am trying to do some Django URL matching.

i want a few urls where i have http://mysite.com/base?sort=type1/, http://mysite.com/base?sort=type2/, etc.

I can't figure out how to URL match these expressions: I'm very new to Django and never used Reg Ex before.

What I have for urls.py in my "base" application is:

url(r'^$','base.views.main, name='main'),

I can't figure out what to put to match my urls with question marks.

I'm trying something like

url(r'^?sort=popular/$', 'base.views.main_popular', name='main_popular'),

Thanks for help!

解决方案

? won't match an "?" inside the url , instead it has its own meaning which you can look it up here :
Python Regular Expressions If you want to match the exact character of "?" inside your url , you have to somehow escape it ( cause it has a meaning in RegExs ) so you might wanna escape it by a "\" (a backslash ) so you would write \?sort ....

EDIT :
Okay so with what you've said in comments , seems here's your problem , main?sort=popular occurs on your url pattern when you are rendering the template for /main/ with the GET method dictionary argument of sort=popular, just write a function that distinguishes between GET and POST , in the GET part , have sth like sort_by = request.GET.get('sort','') and then sort accordingly with the value of sort_by variable, would be sth like :

def main_handler(request):
     if request.method == "POST":
           whatever ... 
     if request.method == "GET" :
           sort_by = request.GET.get('sort','')
           if sort_by:
                 sort by what sort points to 
                 return "the sorted template"
     return render_to_response(the page and it's args)

and let go of that ? inside the url pattern , that's added when you request a page with a GET argument.

这篇关于Django URLS,使用?在URL中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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