Capturing url parameters in request.GET

2018-12-31 18:07发布

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.

标签: django url rest
9条回答
怪性笑人.
2楼-- · 2018-12-31 19:03

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

查看更多
与风俱净
3楼-- · 2018-12-31 19:04

I'd like to add some option of myself, here. Someone would wonder how to set path in 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 urls.py. What you need to set is 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 (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 Url

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

Do not wrap query string in quotes e.g

http://servername:port/domain/search/?q="CA"
查看更多
素衣白纱
4楼-- · 2018-12-31 19:07

Using GET

request.GET["id"]

Using POST

request.POST["id"]
查看更多
登录 后发表回答