如何在 Django 中获取 GET 请求值?
我当前正在定义正则表达式,以便捕获 URL 中的参数,如教程中所述。 如何从 URL 访问参数作为 HttpRequest
对象的一部分?
我的 HttpRequest.GET 当前返回一个空的 QueryDict 对象。
我想学习如何在没有库的情况下做到这一点,这样我就可以更好地了解 Django。
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.
I'd like to learn how to do this without a library, so I can get to know Django better.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(19)
在 Django 中,视图会为您解析路径。
但除此之外,如果您需要解析路径,您可以使用解析模块
Ex - requestPath is -
domain/search/?userName=myUserName
或
domain/search//product/
In Django, views gets the path resolved for you.
But other than that if you need to resolve the path you can use the resolve module
Ex - the requestedPath is -
domain/search/?userName=myUserName
or
domain/search/<userName>/product/<productName>
这是另一个可以实现的替代解决方案:
在 URL 配置中:
在视图中:
This is another alternate solution that can be implemented:
In the URL configuration:
In the views:
views.py
pk 表示 primary_key。
urls.py
views.py
pk means primary_key.
urls.py
您不妨检查 request.META 字典来访问许多有用的东西,例如
PATH_INFO, QUERY_STRING
你说它返回空查询字典
我认为你需要调整你的url以接受必需或可选的args或kwargs
Django 通过 regex 为您提供了所需的所有功能,例如:
有关此内容的更多信息,请访问 django-optional- url 参数
You might as well check request.META dictionary to access many useful things like
PATH_INFO, QUERY_STRING
you said that it returns empty query dict
I think you need to tune your url to accept required or optional args or kwargs
Django got you all the power you need with regrex like:
more about this at django-optional-url-parameters
似乎更推荐使用
request.query_params
。 例如,当 URL 类似于
domain/search/?q=haha
时,您可以使用request.query_params.get('q', None)
https://www.django-rest-framework.org/api-guide/requests/< /a>
“request.query_params 是 request.GET 的更正确命名同义词。
为了使代码更加清晰,我们建议使用 request.query_params 而不是 Django 的标准 request.GET。这样做将有助于使您的代码库更加正确和明显- 任何 HTTP 方法类型都可能包含查询参数,而不仅仅是 GET 请求。”
It seems more recommended to use
request.query_params
. For example,When a URL is like
domain/search/?q=haha
, you would userequest.query_params.get('q', None)
https://www.django-rest-framework.org/api-guide/requests/
"request.query_params is a more correctly named synonym for request.GET.
For clarity inside your code, we recommend using request.query_params instead of the Django's standard request.GET. Doing so will help keep your codebase more correct and obvious - any HTTP method type may include query parameters, not just GET requests."
例如,如果访问以下网址:
那么,您可以获取
views.py
中的参数,如下所示。 *我的回答解释了如何获取Django 中的 GET 请求值列表和我的answer 解释了如何在 Django 中获取POST
请求值:然后,您可以获取
index.html
中的参数,如下所示:For example, if you access the url below:
Then, you can get the parameters in
views.py
as shown below. *My answer explains how to get aGET
request values' list in Django and my answer explains how to getPOST
request values in Django:Then, you can get the parameters in
index.html
as shown below:url参数可以通过
request.query_params
捕获url parameters may be captured by
request.query_params
澄清camflan的解释,假设您有
url(regex=r'^user/(?P\w{1,50})/$', view='views.profile_page')< /code>
http://domain/user/thaiyoshi/?message=Hi
的传入请求URL 调度程序规则将捕获 URL 路径 的部分内容(此处
"user/thaiyoshi/"
) 并将它们与请求对象一起传递给视图函数。查询字符串(此处为
message=Hi
)被解析,参数被存储为request.GET
中的QueryDict
。 不会对 HTTP GET 参数进行进一步的匹配或处理。此视图函数将使用从 URL 路径中提取的部分和查询参数:
作为旁注,您将找到请求方法(在本例中为
"GET"
,对于提交的表单通常 <代码>“POST”)在request.method
中。 在某些情况下,检查它是否符合您的预期很有用。更新:在决定是使用 URL 路径还是查询参数来传递信息时,以下内容可能会有所帮助:
/blog/post/15/
(不是/blog/posts/?id=15
)/blog/post/15/?show_comments=1
或/blog/posts/2008/?sort_by=date&direction=desc
/blog/post/2008/09/30/django-urls/
To clarify camflan's explanation, let's suppose you have
url(regex=r'^user/(?P<username>\w{1,50})/$', view='views.profile_page')
http://domain/user/thaiyoshi/?message=Hi
The URL dispatcher rule will catch parts of the URL path (here
"user/thaiyoshi/"
) and pass them to the view function along with the request object.The query string (here
message=Hi
) is parsed and parameters are stored as aQueryDict
inrequest.GET
. No further matching or processing for HTTP GET parameters is done.This view function would use both parts extracted from the URL path and a query parameter:
As a side note, you'll find the request method (in this case
"GET"
, and for submitted forms usually"POST"
) inrequest.method
. In some cases, it's useful to check that it matches what you're expecting.Update: When deciding whether to use the URL path or the query parameters for passing information, the following may help:
/blog/post/15/
(not/blog/posts/?id=15
)/blog/post/15/?show_comments=1
or/blog/posts/2008/?sort_by=date&direction=desc
/blog/post/2008/09/30/django-urls/
给出网址:
域名/搜索/?q=haha
用途:
request.GET.get('q', 'default')
。q
是参数,如果未找到q
,则'default'
是默认值。但是,如果您只是配置
URLconf
**,则从regex
捕获的内容将作为参数(或命名参数)传递给函数。例如:
那么在你的views.py中你就会有
Give URL:
domain/search/?q=haha
use:
request.GET.get('q', 'default')
.q
is the parameter, and'default'
is the default value ifq
isn't found.However, if you are instead just configuring your
URLconf
**, then your captures from theregex
are passed to the function as arguments (or named arguments).Such as:
Then in your
views.py
you would have使用 GET
使用 POST
Using GET
Using POST
有人会想知道如何在文件 urls.py 中设置路径,以便
我们可以调用查询。
事实上,没有必要在文件urls.py中设置这样的路由。 您只需在 urls.py 中设置路由:
当您输入 http://servername:port/domain/search/?q=CA 时。 查询部分'?q=CA'将自动保留在哈希表中,您可以参考
这里是一个示例(文件views.py)
此外,当您在URL中写入查询字符串时:
不要将查询字符串括在引号中。 例如,
Someone would wonder how to set path in file urls.py, such as
so that we could invoke query.
The fact is that it is not necessary to set such a route in file urls.py. You need to set just the route in urls.py:
And when you input http://servername:port/domain/search/?q=CA. The query part '?q=CA' will be automatically reserved in the hash table which you can reference though
Here is an example (file views.py)
In addition, when you write query string in the URL:
Do not wrap query string in quotes. For example,
对于只有
request
对象的情况,您可以使用request.parser_context['kwargs']['your_param']
For situations where you only have the
request
object you can userequest.parser_context['kwargs']['your_param']
这些查询目前通过两种方式完成。 如果要访问查询参数(GET)可以查询如下:
如果要访问POST传递的参数,则需要这样访问:
用'get()'访问字典(QueryDict),可以设置默认值。 在上述情况下,如果未告知“状态”或“角色”,则值为“无”。
These queries are currently done in two ways. If you want to access the query parameters (GET) you can query the following:
If you want to access the parameters passed by POST, you need to access this way:
Accessing the dictionary (QueryDict) with 'get()', you can set a default value. In the cases above, if 'status' or 'role' are not informed, the values are None.
我想分享一个可能会节省您一些时间的技巧。
如果您打算在
urls.py
文件中使用类似的内容:这基本上意味着
www.example.com/
。 请务必将其放在 URL 条目的末尾,否则很容易与下面的 URL 条目发生冲突,即访问其中一个将给出不错的错误:< code>用户匹配查询不存在。我刚刚亲身经历过; 希望能帮助到你!
I would like to share a tip that may save you some time.
If you plan to use something like this in your
urls.py
file:Which basically means
www.example.com/<username>
. Be sure to place it at the end of your URL entries, because otherwise, it is prone to cause conflicts with the URL entries that follow below, i.e. accessing one of them will give you the nice error:User matching query does not exist.
I've just experienced it myself; hope it helps!
如果您的 URL 如下所示,您有两种常见的方法可以做到这一点:
版本 1:
如果特定键是必需的,您可以使用:
如果该键存在并且 <,这将返回
a
值em>例外如果没有。版本 2:
如果您的密钥是可选的:
您可以尝试不带任何参数,这不会崩溃。
因此,您可以在示例中使用
try: except:
包装它并返回HttpResponseBadRequest()
。这是一种降低代码复杂性的简单方法,无需使用特殊的异常处理。
You have two common ways to do that in case your URL looks like that:
Version 1:
If a specific key is mandatory you can use:
This will return a value of
a
if the key exists and an exception if not.Version 2:
If your keys are optional:
You can try that without any argument and this will not crash.
So you can wrap it with
try: except:
and returnHttpResponseBadRequest()
in example.This is a simple way to make your code less complex, without using special exceptions handling.
如果您不知道参数的名称并希望使用所有参数,可以使用
request.GET.keys()
或dict(request.GET)
函数If you don't know the name of params and want to work with them all, you can use
request.GET.keys()
ordict(request.GET)
functions这并不完全是您所要求的,但是此代码段对于管理
query_strings很有帮助
在模板
中。This is not exactly what you asked for, but this snippet is helpful for managing
query_strings
intemplates
.如果您只能访问视图对象,则可以通过以下方式获取 URL 路径中定义的参数:
如果您只能访问请求对象,请使用以下内容:
在 Django 3 上测试。
If you only have access to the view object, then you can get the parameters defined in the URL path this way:
If you only have access to the request object, use the following:
Tested on Django 3.