1

I am creating an api in django in which I have a parameter (state_name) and the value of state_name can include '&' in its value which is causing certain problems ?

For example if my url is like

http://localhost:8080/api?state_name=jammu&kashmir&value=2

so in the above example when i try to fetch the values from the url it takes the value of state_name only 'jammu' and treats kashmir as a parameter?

What can i do to resolve this issue in django ?

3
  • Is there any problem with jammu and kashmir ? Commented Nov 1, 2018 at 11:48
  • yes in my db its jammu&kasmir and to change that will be a big change? Commented Nov 1, 2018 at 11:49
  • This is actually more about URL syntax than about django. I would explain, but the answers below explain even better than I would have been able to. Commented Nov 1, 2018 at 11:59

2 Answers 2

6

You need to escape the & for use in http query parameters.

http://localhost:8080/api?state_name=jammu%26kashmir&value=2

If you're posting this from another Python script, you can use the urllib.parse.quote function to do it for you:

from urllib import parse
parse.quote("jammu&kashmir") # jammu%26kashmir
Sign up to request clarification or add additional context in comments.

Comments

1

I am creating an api in django in which I have a parameter (state_name) and the value of state_name can include '&' in its value which is causing certain problems?

This is nonsensical. In a querystring, two parameters are separated by an ampersand (&). For example:

foo=bar&qux=3

If you want the content to contain an ampersand, you need to encode it, like:

?state_name=jammu%26kashmir&value=2

Here %26 is the encoding of the ampersand, and then the querystring has two parameters: state_name and value. These are then parsed like:

>>> from django.http import QueryDict
>>> QueryDict('state_name=jammu%26kashmir&value=2')
<QueryDict: {'state_name': ['jammu&kashmir'], 'value': ['2']}>

You can use a QueryDict to construct such query, for example:

>>> qd = QueryDict(mutable=True)
>>> qd['state_name'] = 'jammu&kashmir'
>>> qd['value'] = '2'
>>> qd.urlencode()
'state_name=jammu%26kashmir&value=2'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.