如何在 Django 中获取 GET 请求值?

发布于 2024-07-06 01:00:36 字数 191 浏览 11 评论 0原文

我当前正在定义正则表达式,以便捕获 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(19

记忆之渊 2024-07-13 01:00:37

在 Django 中,视图会为您解析路径。

但除此之外,如果您需要解析路径,您可以使用解析模块

Ex - requestPath is - domain/search/?userName=myUserName
domain/search//product/

from django.urls import resolve
resolveMatcher = resolve(request.path)
userName = resolveMatcher.kwargs.get('userName', None)

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>

from django.urls import resolve
resolveMatcher = resolve(request.path)
userName = resolveMatcher.kwargs.get('userName', None)
宫墨修音 2024-07-13 01:00:37

这是另一个可以实现的替代解决方案:

在 URL 配置中:

urlpatterns = [path('runreport/<str:queryparams>', views.get)]

在视图中:

list2 = queryparams.split("&")

This is another alternate solution that can be implemented:

In the URL configuration:

urlpatterns = [path('runreport/<str:queryparams>', views.get)]

In the views:

list2 = queryparams.split("&")
做个ˇ局外人 2024-07-13 01:00:37

views.py

from rest_framework.response import Response

def update_product(request, pk):
    return Response({"pk":pk})

pk 表示 primary_key

urls.py

from products.views import update_product
from django.urls import path

urlpatterns = [
    ...,
    path('update/products/<int:pk>', update_product)
]

views.py

from rest_framework.response import Response

def update_product(request, pk):
    return Response({"pk":pk})

pk means primary_key.

urls.py

from products.views import update_product
from django.urls import path

urlpatterns = [
    ...,
    path('update/products/<int:pk>', update_product)
]

池予 2024-07-13 01:00:37

您不妨检查 request.META 字典来访问许多有用的东西,例如
PATH_INFO, QUERY_STRING

# for example
request.META['QUERY_STRING']

# or to avoid any exceptions provide a fallback

request.META.get('QUERY_STRING', False)

你说它返回空查询字典

我认为你需要调整你的url以接受必需或可选的args或kwargs
Django 通过 regex 为您提供了所需的所有功能,例如:

url(r'^project_config/(?P<product>\w+)/

有关此内容的更多信息,请访问 django-optional- url 参数

, views.foo),

有关此内容的更多信息,请访问 django-optional- url 参数

You might as well check request.META dictionary to access many useful things like
PATH_INFO, QUERY_STRING

# for example
request.META['QUERY_STRING']

# or to avoid any exceptions provide a fallback

request.META.get('QUERY_STRING', False)

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:

url(r'^project_config/(?P<product>\w+)/

more about this at django-optional-url-parameters

, views.foo),

more about this at django-optional-url-parameters

A君 2024-07-13 01:00:37

似乎更推荐使用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 use request.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."

忆梦 2024-07-13 01:00:37

例如,如果访问以下网址:

https://example.com/?fruits=apple&meat=beef

那么,您可以获取views.py中的参数,如下所示。 *我的回答解释了如何获取Django 中的 GET 请求值列表和我的answer 解释了如何在 Django 中获取 POST 请求值:

# "views.py"

from django.shortcuts import render

def index(request):

    print(request.GET['fruits']) # apple
    print(request.GET.get('meat')) # beef
    print(request.GET.get('fish')) # None
    print(request.GET.get('fish', "Doesn't exist")) # Doesn't exist
    print(request.GET.getlist('fruits')) # ['apple']
    print(request.GET.getlist('fish')) # []
    print(request.GET.getlist('fish', "Doesn't exist")) # Doesn't exist
    print(request.GET._getlist('meat')) # ['beef']
    print(request.GET._getlist('fish')) # []
    print(request.GET._getlist('fish', "Doesn't exist")) # Doesn't exist
    print(list(request.GET.keys())) # ['fruits', 'meat']
    print(list(request.GET.values())) # ['apple', 'beef']
    print(list(request.GET.items())) # [('fruits', 'apple'), ('meat', 'beef')]
    print(list(request.GET.lists())) # [('fruits', ['apple']), ('meat', ['beef'])]
    print(request.GET.dict()) # {'fruits': 'apple', 'meat': 'beef'}
    print(dict(request.GET)) # {'fruits': ['apple'], 'meat': ['beef']}
    print(request.META['QUERY_STRING']) # fruits=apple&meat=beef
    print(request.META.get('QUERY_STRING')) # fruits=apple&meat=beef

    return render(request, 'index.html')

然后,您可以获取 index.html 中的参数,如下所示:

{# "index.html" #}

{{ request.GET.fruits }} {# apple #}
{{ request.GET.meat }} {# beef #}
{{ request.GET.dict }} {# {'fruits': 'apple', 'meat': 'beef'} #}
{{ request.META.QUERY_STRING }} {# fruits=apple&meat=beef #}

For example, if you access the url below:

https://example.com/?fruits=apple&meat=beef

Then, you can get the parameters in views.py as shown below. *My answer explains how to get a GET request values' list in Django and my answer explains how to get POST request values in Django:

# "views.py"

from django.shortcuts import render

def index(request):

    print(request.GET['fruits']) # apple
    print(request.GET.get('meat')) # beef
    print(request.GET.get('fish')) # None
    print(request.GET.get('fish', "Doesn't exist")) # Doesn't exist
    print(request.GET.getlist('fruits')) # ['apple']
    print(request.GET.getlist('fish')) # []
    print(request.GET.getlist('fish', "Doesn't exist")) # Doesn't exist
    print(request.GET._getlist('meat')) # ['beef']
    print(request.GET._getlist('fish')) # []
    print(request.GET._getlist('fish', "Doesn't exist")) # Doesn't exist
    print(list(request.GET.keys())) # ['fruits', 'meat']
    print(list(request.GET.values())) # ['apple', 'beef']
    print(list(request.GET.items())) # [('fruits', 'apple'), ('meat', 'beef')]
    print(list(request.GET.lists())) # [('fruits', ['apple']), ('meat', ['beef'])]
    print(request.GET.dict()) # {'fruits': 'apple', 'meat': 'beef'}
    print(dict(request.GET)) # {'fruits': ['apple'], 'meat': ['beef']}
    print(request.META['QUERY_STRING']) # fruits=apple&meat=beef
    print(request.META.get('QUERY_STRING')) # fruits=apple&meat=beef

    return render(request, 'index.html')

Then, you can get the parameters in index.html as shown below:

{# "index.html" #}

{{ request.GET.fruits }} {# apple #}
{{ request.GET.meat }} {# beef #}
{{ request.GET.dict }} {# {'fruits': 'apple', 'meat': 'beef'} #}
{{ request.META.QUERY_STRING }} {# fruits=apple&meat=beef #}
栩栩如生 2024-07-13 01:00:37

url参数可以通过request.query_params捕获

url parameters may be captured by request.query_params

绿光 2024-07-13 01:00:36

澄清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 路径中提取的部分和查询参数:

def profile_page(request, username=None):
    user = User.objects.get(username=username)
    message = request.GET.get('message')

作为旁注,您将找到请求方法(在本例中为 "GET",对于提交的表单通常 <代码>“POST”)在request.method中。 在某些情况下,检查它是否符合您的预期很有用。

更新:在决定是使用 URL 路径还是查询参数来传递信息时,以下内容可能会有所帮助:

  • 使用 URL 路径来唯一标识资源,例如 /blog/post/15/(不是/blog/posts/?id=15
  • 使用查询参数来更改资源的显示方式,例如/blog/post/15/?show_comments=1/blog/posts/2008/?sort_by=date&direction=desc
  • 来制作人性化的 URL,避免使用 ID 号并使用日期、类别和/或 slugs: /blog/post/2008/09/30/django-urls/

To clarify camflan's explanation, let's suppose you have

  • the rule url(regex=r'^user/(?P<username>\w{1,50})/$', view='views.profile_page')
  • an incoming request for 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 a QueryDict in request.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:

def profile_page(request, username=None):
    user = User.objects.get(username=username)
    message = request.GET.get('message')

As a side note, you'll find the request method (in this case "GET", and for submitted forms usually "POST") in request.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:

  • use the URL path for uniquely identifying resources, e.g. /blog/post/15/ (not /blog/posts/?id=15)
  • use query parameters for changing the way the resource is displayed, e.g. /blog/post/15/?show_comments=1 or /blog/posts/2008/?sort_by=date&direction=desc
  • to make human-friendly URLs, avoid using ID numbers and use e.g. dates, categories, and/or slugs: /blog/post/2008/09/30/django-urls/
狠疯拽 2024-07-13 01:00:36

给出网址:
域名/搜索/?q=haha
用途:
request.GET.get('q', 'default')

q 是参数,如果未找到 q,则 'default' 是默认值。

但是,如果您只是配置 URLconf**,则从 regex 捕获的内容将作为参数(或命名参数)传递给函数。

例如:

(r'^user/(?P<username>\w{0,50})/

那么在你的views.py中你就会有

def profile_page(request, username):
    # Rest of the method
, views.profile_page,),

那么在你的views.py中你就会有

Give URL:
domain/search/?q=haha
use:
request.GET.get('q', 'default').

q is the parameter, and 'default' is the default value if q isn't found.

However, if you are instead just configuring your URLconf**, then your captures from the regex are passed to the function as arguments (or named arguments).

Such as:

(r'^user/(?P<username>\w{0,50})/

Then in your views.py you would have

def profile_page(request, username):
    # Rest of the method
, views.profile_page,),

Then in your views.py you would have

清风无影 2024-07-13 01:00:36

使用 GET

request.GET["id"]

使用 POST

request.POST["id"]

Using GET

request.GET["id"]

Using POST

request.POST["id"]
静水深流 2024-07-13 01:00:36

有人会想知道如何在文件 urls.py 中设置路径,以便

domain/search/?q=CA

我们可以调用查询。

事实上,没有必要在文件urls.py中设置这样的路由。 您只需在 urls.py 中设置路由:

urlpatterns = [
    path('domain/search/', views.CityListView.as_view()),
]

当您输入 http://servername:port/domain/search/?q=CA 时。 查询部分'?q=CA'将自动保留在哈希表中,您可以参考

request.GET.get('q', None).

这里是一个示例(文件views.py

class CityListView(generics.ListAPIView):
    serializer_class = CityNameSerializer

    def get_queryset(self):
        if self.request.method == 'GET':
            queryset = City.objects.all()
            state_name = self.request.GET.get('q', None)
            if state_name is not None:
                queryset = queryset.filter(state__name=state_name)
            return queryset

此外,当您在URL中写入查询字符串时:

http://servername:port/domain/search/?q=CA

不要将查询字符串括在引号中。 例如,

http://servername:port/domain/search/?q="CA"

Someone would wonder how to set path in file urls.py, such as

domain/search/?q=CA

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:

urlpatterns = [
    path('domain/search/', views.CityListView.as_view()),
]

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

request.GET.get('q', None).

Here is an example (file views.py)

class CityListView(generics.ListAPIView):
    serializer_class = CityNameSerializer

    def get_queryset(self):
        if self.request.method == 'GET':
            queryset = City.objects.all()
            state_name = self.request.GET.get('q', None)
            if state_name is not None:
                queryset = queryset.filter(state__name=state_name)
            return queryset

In addition, when you write query string in the URL:

http://servername:port/domain/search/?q=CA

Do not wrap query string in quotes. For example,

http://servername:port/domain/search/?q="CA"
不再见 2024-07-13 01:00:36

对于只有 request 对象的情况,您可以使用 request.parser_context['kwargs']['your_param']

For situations where you only have the request object you can use request.parser_context['kwargs']['your_param']

怪异←思 2024-07-13 01:00:36
def some_view(request, *args, **kwargs):
    if kwargs.get('q', None):
        # Do something here ..
def some_view(request, *args, **kwargs):
    if kwargs.get('q', None):
        # Do something here ..
み青杉依旧 2024-07-13 01:00:36

这些查询目前通过两种方式完成。 如果要访问查询参数(GET)可以查询如下:

http://myserver:port/resource/?status=1
request.query_params.get('status', None) => 1

如果要访问POST传递的参数,则需要这样访问:

request.data.get('role', None)

用'get()'访问字典(QueryDict),可以设置默认值。 在上述情况下,如果未告知“状态”或“角色”,则值为“无”。

These queries are currently done in two ways. If you want to access the query parameters (GET) you can query the following:

http://myserver:port/resource/?status=1
request.query_params.get('status', None) => 1

If you want to access the parameters passed by POST, you need to access this way:

request.data.get('role', None)

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.

情深缘浅 2024-07-13 01:00:36

我想分享一个可能会节省您一些时间的技巧。
如果您打算在 urls.py 文件中使用类似的内容:

url(r'^(?P<username>\w+)/

这基本上意味着 www.example.com/。 请务必将其放在 URL 条目的末尾,否则很容易与下面的 URL 条目发生冲突,即访问其中一个给出不错的错误:< code>用户匹配查询不存在。

我刚刚亲身经历过; 希望能帮助到你!

, views.profile_page,),

这基本上意味着 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:

url(r'^(?P<username>\w+)/

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!

, views.profile_page,),

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!

离线来电— 2024-07-13 01:00:36

如果您的 URL 如下所示,您有两种常见的方法可以做到这一点:

https://domain/method/?a=x&b=y

版本 1:

如果特定键是必需的,您可以使用:

key_a = request.GET['a']

如果该键存在并且 <,这将返回 a 值em>例外如果没有。

版本 2:

如果您的密钥是可选的:

request.GET.get('a')

您可以尝试不带任何参数,这不会崩溃。
因此,您可以在示例中使用 try: except: 包装它并返回 HttpResponseBadRequest()
这是一种降低代码复杂性的简单方法,无需使用特殊的异常处理。

You have two common ways to do that in case your URL looks like that:

https://domain/method/?a=x&b=y

Version 1:

If a specific key is mandatory you can use:

key_a = request.GET['a']

This will return a value of a if the key exists and an exception if not.

Version 2:

If your keys are optional:

request.GET.get('a')

You can try that without any argument and this will not crash.
So you can wrap it with try: except: and return HttpResponseBadRequest() in example.
This is a simple way to make your code less complex, without using special exceptions handling.

养猫人 2024-07-13 01:00:36

如果您不知道参数的名称并希望使用所有参数,可以使用 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() or dict(request.GET) functions

暗地喜欢 2024-07-13 01:00:36

这并不完全是您所要求的,但是此代码段对于管理query_strings很有帮助模板中。

This is not exactly what you asked for, but this snippet is helpful for managing query_strings in templates.

轻许诺言 2024-07-13 01:00:36

如果您只能访问视图对象,则可以通过以下方式获取 URL 路径中定义的参数:

view.kwargs.get('url_param')

如果您只能访问请求对象,请使用以下内容:

request.resolver_match.kwargs.get('url_param')

在 Django 3 上测试。

If you only have access to the view object, then you can get the parameters defined in the URL path this way:

view.kwargs.get('url_param')

If you only have access to the request object, use the following:

request.resolver_match.kwargs.get('url_param')

Tested on Django 3.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文