Capturing URL parameters in request.GET

后端 未结 13 835
说谎
说谎 2020-11-22 08:30

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

相关标签:
13条回答
  • 2020-11-22 08:45

    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("&")
    
    0 讨论(0)
  • 2020-11-22 08:48

    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.

    0 讨论(0)
  • 2020-11-22 08:49

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

    0 讨论(0)
  • 2020-11-22 08:51

    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+)/$', 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!

    0 讨论(0)
  • 2020-11-22 08:53

    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+)/$', views.foo),
    
    

    more about this at django-optional-url-parameters

    0 讨论(0)
  • 2020-11-22 08:56
    def some_view(request, *args, **kwargs):
        if kwargs.get('q', None):
            # Do something here ..
    
    0 讨论(0)
提交回复
热议问题