425
This is not specific to Django, but for Python in general. For a Django specific answer, see this one from @jball037
Python 2:
import urlparse
url = 'https://www.example.com/some_path?some_key=some_value'
parsed = urlparse.urlparse(url)
captured_value = urlparse.parse_qs(parsed.query)['some_key'][0]
print captured_value
Python 3:
from urllib.parse import urlparse
from urllib.parse import parse_qs
url = 'https://www.example.com/some_path?some_key=some_value'
parsed_url = urlparse(url)
captured_value = parse_qs(parsed_url.query)['some_key'][0]
print(captured_value)
parse_qs
returns a list. The [0]
gets the first item of the list so the output of each script is some_value
91
I’m shocked this solution isn’t on here already. Use:
request.GET.get('variable_name')
This will “get” the variable from the “GET” dictionary, and return the ‘variable_name’ value if it exists, or a None object if it doesn’t exist.
- [Django]-Use Python standard logging in Celery
- [Django]-DatabaseError: current transaction is aborted, commands ignored until end of transaction block?
- [Django]-Django JSONField inside ArrayField
70
for Python > 3.4
from urllib import parse
url = 'http://foo.appspot.com/abc?def=ghi'
query_def=parse.parse_qs(parse.urlparse(url).query)['def'][0]
- [Django]-Do django db_index migrations run concurrently?
- [Django]-How to use MySQLdb with Python and Django in OSX 10.6?
- [Django]-Passing STATIC_URL to file javascript with django
64
import urlparse
url = 'http://example.com/?q=abc&p=123'
par = urlparse.parse_qs(urlparse.urlparse(url).query)
print par['q'][0], par['p'][0]
- [Django]-How to customize activate_url on django-allauth?
- [Django]-How do I match the question mark character in a Django URL?
- [Django]-Django – iterate number in for loop of a template
35
There is a new library called furl. I find this library to be most pythonic for doing url algebra.
To install:
pip install furl
Code:
from furl import furl
f = furl("/abc?def='ghi'")
print f.args['def']
- [Django]-Testing nginx without domain name
- [Django]-Django rest framework, use different serializers in the same ModelViewSet
- [Django]-Suddenly when running tests I get "TypeError: 'NoneType' object is not iterable
21
I know this is a bit late but since I found myself on here today, I thought that this might be a useful answer for others.
import urlparse
url = 'http://example.com/?q=abc&p=123'
parsed = urlparse.urlparse(url)
params = urlparse.parse_qsl(parsed.query)
for x,y in params:
print "Parameter = "+x,"Value = "+y
With parse_qsl(), “Data are returned as a list of name, value pairs.”
- [Django]-Stack trace from manage.py runserver not appearing
- [Django]-Creating email templates with Django
- [Django]-How do I do an OR filter in a Django query?
7
The url you are referring is a query type and I see that the request object supports a method called arguments to get the query arguments. You may also want try self.request.get('def')
directly to get your value from the object..
- [Django]-What is the purpose of adding to INSTALLED_APPS in Django?
- [Django]-What's the purpose of Django setting ‘SECRET_KEY’?
- [Django]-Custom django admin templates not working
7
In pure Python:
def get_param_from_url(url, param_name):
return [i.split("=")[-1] for i in url.split("?", 1)[-1].split("&") if i.startswith(param_name + "=")][0]
- [Django]-Using JSON in django template
- [Django]-How to monkey patch Django?
- [Django]-Logging in Django and gunicorn
6
def getParams(url):
params = url.split("?")[1]
params = params.split('=')
pairs = zip(params[0::2], params[1::2])
answer = dict((k,v) for k,v in pairs)
Hope this helps
- [Django]-How can I activate the unaccent extension on an already existing model
- [Django]-Django: Use of DATE_FORMAT, DATETIME_FORMAT, TIME_FORMAT in settings.py?
- [Django]-Setting DEBUG = False causes 500 Error
- [Django]-Django aggregate or annotate
- [Django]-Django – limiting query results
- [Django]-Is there a way to filter a queryset in the django admin?
4
There’s not need to do any of that. Only with
self.request.get('variable_name')
Notice that I’m not specifying the method (GET, POST, etc). This is well documented and this is an example
The fact that you use Django templates doesn’t mean the handler is processed by Django as well
- [Django]-Django: how save bytes object to models.FileField?
- [Django]-Missing Table When Running Django Unittest with Sqlite3
- [Django]-How to add a cancel button to DeleteView in django
3
import cgitb
cgitb.enable()
import cgi
print "Content-Type: text/plain;charset=utf-8"
print
form = cgi.FieldStorage()
i = int(form.getvalue('a'))+int(form.getvalue('b'))
print i
- [Django]-How do I use an UpdateView to update a Django Model?
- [Django]-OneToOneField() vs ForeignKey() in Django
- [Django]-Images from ImageField in Django don't load in template
3
Most answers here suggest using parse_qs
to parse an URL string. This method always returns the values as a list (not directly as a string) because a parameter can appear multiple times, e.g.:
http://example.com/?foo=bar&foo=baz&bar=baz
Would return:
{'foo': ['bar', 'baz'], 'bar' : ['baz']}
This is a bit inconvenient because in most cases you’re dealing with an URL that doesn’t have the same parameter multiple times. This function returns the first value by default, and only returns a list if there’s more than one element.
from urllib import parse
def parse_urlargs(url):
query = parse.parse_qs(parse.urlparse(url).query)
return {k:v[0] if v and len(v) == 1 else v for k,v in query.items()}
For example, http://example.com/?foo=bar&foo=baz&bar=baz
would return:
{'foo': ['bar', 'baz'], 'bar': 'baz'}
- [Django]-Execute code when Django starts ONCE only?
- [Django]-Django models: mutual references between two classes and impossibility to use forward declaration in python
- [Django]-Django-allauth: Linking multiple social accounts to a single user
2
There is a nice library w3lib.url
from w3lib.url import url_query_parameter
url = "/abc?def=ghi"
print url_query_parameter(url, 'def')
ghi
- [Django]-Using django-rest-interface
- [Django]-How do I reuse HTML snippets in a django view
- [Django]-Django REST Framework (DRF): Set current user id as field value
2
Parsing it in raw python:
path = '/some_path?k1=v1&k2=v2&k3=v3'
_, query_string = path.split('?')
params = dict(param.split('=') for param in query_string.split('&'))
print(params)
Output:
{'k1': 'v1', 'k2': 'v2', 'k3': 'v3'}
- [Django]-Django content-type : how do I get an object?
- [Django]-How to change empty_label for modelForm choice field?
- [Django]-Django TypeError: get() got multiple values for keyword argument 'invoice_id'
0
Btw, I was having issues using parse_qs() and getting empty value parameters and learned that you have to pass a second optional parameter ‘keep_blank_values’ to return a list of the parameters in a query string that contain no values. It defaults to false. Some crappy written APIs require parameters to be present even if they contain no values
for k,v in urlparse.parse_qs(p.query, True).items():
print k
- [Django]-Why is logged_out.html not overriding in django registration?
- [Django]-Celery. Decrease number of processes
- [Django]-How can I activate the unaccent extension on an already existing model
0
parameters = dict([part.split(‘=’) for part in
get_parsed_url[4].split(‘&’)])
This one is simple. The variable parameters will contain a dictionary of all the parameters.
- [Django]-In a Django form, how do I make a field readonly (or disabled) so that it cannot be edited?
- [Django]-How do I get user IP address in Django?
- [Django]-How can I access environment variables directly in a Django template?
0
I see there isn’t an answer for users of Tornado:
key = self.request.query_arguments.get("key", None)
This method must work inside an handler that is derived from:
tornado.web.RequestHandler
None is the answer this method will return when the requested key can’t be found. This saves you some exception handling.
- [Django]-How to get username from Django Rest Framework JWT token
- [Django]-Django queryset filter – Q() | VS __in
- [Django]-Use Python standard logging in Celery
0
I didn’t want to mess with additional libraries. Simple ways suggested here didn’t work out either. Finally, not on the request object, but I could get a GET parameter w/o all that hassle via self.GET.get('XXX')
:
...
def get_context_data(self, **kwargs):
context = super(SomeView, self).get_context_data(**kwargs)
context['XXX'] = self.GET.get('XXX')
...
Python 2.7.18, Django 1.11.20
- [Django]-Django auto_now and auto_now_add
- [Django]-Django migration fails with "__fake__.DoesNotExist: Permission matching query does not exist."
- [Django]-(13: Permission denied) while connecting to upstream:[nginx]
0
NOT using Django and tried on Python 3.9. It can also be retrieved using the below code snippet in the handler:
considering URL as-
http://localhost:8081/api/v1/users?query_key=abcdef12345
and handler method as:
@routes.get('/api/v1/users')
async def handler_users(request):
query_key = request.url.query['query_key']
- [Django]-Favorite Django Tips & Features?
- [Django]-Django values_list vs values
- [Django]-How do you configure Django to send mail through Postfix?
0
You can use only request.GET.get() method
urls.py:
path('some_path', views.func),
views.py:
def func(request):
some_key = request.GET.get('some_key', None)
...
- [Django]-Django project models.py versus app models.py
- [Django]-Difference between User.objects.create_user() vs User.objects.create() vs User().save() in django
- [Django]-How to completely dump the data for Django-CMS