问题描述
正如本教程所述,我正在定义正则表达式以捕获url中的参数。如何从url访问参数作为 HttpRequest
对象的一部分?我的 HttpRequest.GET
目前返回一个空的 QueryDict
对象。
I am currently defining regular expressions in order to capture parameters in a url, as described in the tutorial. How do I access parameters from the url as part the HttpRequest
object? My HttpRequest.GET
currently returns an empty QueryDict
object.
我想学习如何在没有图书馆的情况下做到这一点,所以我可以更好地了解Django。
I'd like to learn how to do this without a library so I can get to know Django better.
推荐答案
如果您的网址类似于 domain / search /?q = haha
,然后你将使用 request.GET.get('q','')
。
If your url is something like domain/search/?q=haha
, Then you would use request.GET.get('q', '')
.
q
是您想要的参数,而''
是默认值,如果 q
没有找到。
q
is the parameter you want, And ''
is the default value if q
isn't found.
如果你只是配置你的 URLconf
,那么你的捕获将 regex
作为参数(或命名参数)传递给该函数。
If you are instead just configuring your URLconf
, Then your captures from the regex
are passed to the function as arguments (or named arguments).
如:
(r'^user/(?P<username>\w{0,50})/$', views.profile_page,),
然后在您的 views.py
将有
def profile_page(request, username):
# Rest of the method
这篇关于捕获请求中的url参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!