Django接受GET参数 [英] Django accepting GET parameters
问题描述
可以在这里看到错误: http://djaffry.selfip.com:8080/
我希望索引页接受参数,无论是
mysite.com/search/param_here
或
mysite.com/?search=param_here
我在我的URL模式中有这个,但我不能让它工作。任何建议?
urlpatterns = patterns('',
(r'^ $ /(?P< tag> \w +)','twingle.search.views.index'),
)
首先你的URL格式的正则表达式是错误的。
r'^ $ /(?P< tag> \w +)'
p>
- ^开始行
- $到行尾
- 具有模式命名标签,由行尾结束后的字和数字
通常在一行结束是另一行或EOF不是内容(除非你使用多行正则表达式,你不需要这些)。
行结束应该在标签之后:
r'^ /(?P< tag> \w +)$'
使用查询字符串
因此,如果您的格式为url:
http://mysite.com/?query=param_here
将匹配:
(r'^ $','twingle.search.views.index')
在这种情况下,您可以访问查询
string如下所示:
request.GET.get('query','')
没有查询字符串
mysite.com/search/param_here
将匹配:
(r'^ search /(?P< query> \w +)$','twingle.search.views.index'),
凡与 \w
匹配的所有内容应该改变这个来满足你的需要)wil l请求索引视图函数作为参数查询
。
两者
您可以使用这两种网址格式:
urlpatterns = patterns('twingle.search.views',
url(r'^ $','index'),
url(r'^ search /(?P< query> \w +)$ ','index'),
)
在这个例子中,视图看起来像这个:
def index(request,query = None)
如果没有查询:
query = request .GET.get('query','')
#使用`query` string
Error can be seen here: http://djaffry.selfip.com:8080/
I want the index page to accept parameters, whether it be
mysite.com/search/param_here
or
mysite.com/?search=param_here
I have this in my URL patterns, but I can't get it to work. Any suggestions?
urlpatterns = patterns('',
(r'^$/(?P<tag>\w+)', 'twingle.search.views.index'),
)
First of all your regular expression in url pattern is wrong.
r'^$/(?P<tag>\w+)'
It says to match everything from
- ^ the beginning of line
- $ to the end of line
- having pattern named tag which is composed of words and digits after the line end
Usually after the one line ends comes another line or EOF not content (unless you use multiline regexp and you don't need those here).
Line end should be after the tag:
r'^/(?P<tag>\w+)$'
Using a query string
Query strings are not parsed by url reslover.
Thus, if you have url in format:
http://mysite.com/?query=param_here
will match:
(r'^$', 'twingle.search.views.index')
In this case you can access query
string in view like so:
request.GET.get('query', '')
Without a query string
mysite.com/search/param_here
will match:
(r'^search/(?P<query>\w+)$', 'twingle.search.views.index'),
Where everything that matches \w
(you should change this to suite your needs) will be passed along with request to index view function as argument named query
.
Both
You can use both url patterns like so:
urlpatterns = patterns('twingle.search.views',
url(r'^$', 'index'),
url(r'^search/(?P<query>\w+)$', 'index'),
)
In this example the view would look something like this:
def index(request, query=None)
if not query:
query = request.GET.get('query', '')
# do stuff with `query` string
这篇关于Django接受GET参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!