How to Retrieve GET Request Values in Django
In Django, extracting GET request values from the HttpRequest object can be accomplished without the use of external libraries.
Problem:
Accessing GET parameters from the URL using the HttpRequest.GET property results in an empty QueryDict object.
Solution:
To retrieve GET request values directly from HttpRequest, use the following syntax:
request.GET.get('parameter_name', 'default_value')
Example:
To retrieve the 'q' parameter from the URL "domain/search/?q=haha":
q_value = request.GET.get('q', 'default')
The variable 'q_value' will now hold the value 'haha'.
Note for URL Configuration:
If GET parameters are captured using regular expressions in the URLconf, they are passed to the associated view function as arguments or named arguments. The regular expression captures are available within these functions.
For instance, consider the following URL configuration:
(r'^user/(?P<username>\w{0,50})/$', views.profile_page),
In views.py, the profile_page view function would look like this:
def profile_page(request, username): # View logic goes here
In this case, the 'username' GET parameter is passed as the 'username' argument to the profile_page function.
The above is the detailed content of How to Access GET Request Parameters in Django?. For more information, please follow other related articles on the PHP Chinese website!