ELsssss
ELsssss

Reputation: 206

Django: How to decode the url to get the variable value?

I'm trying to do django api.

Here is the code in urls.py

url(r'^edit/(?P<name>[\w-]+)/$', UpdateView.as_view(), name="update")

views.py

class UpdateView(RetrieveUpdateView):
     queryset = Book.objects.all()
     serializer_class = BookUpdateSerializer
     lookup_field = "name"

The name variable might include '|' symbol.

When I open URL 127.0.0.1:8000/api/edit/ABCD|1234 in my browser, where ABCD|1234 is the variable name, the url will automatically encode it, and it becomes 127.0.0.1:8000/api/edit/ABCD%7C1234.

It can't find this name from my database. How can I decode it and retrieve data from my database?

Upvotes: 1

Views: 552

Answers (1)

Alasdair
Alasdair

Reputation: 308839

Django will decode the url for you. When you access self.kwargs['name'], it will be 'ABCD|1234', not 'ABCD%7C1234'.

However, you have a separate issue. Your current regex group [\w-]+ will only match upper case A-Z, lowercase a-z, digits 0-9, underscore _ and hyphen -. You'll have to change this if you want to match characters like |.

You could simply add | to the group:

# put | before - otherwise you have to escape hypen with \-
url(r'^edit/(?P<name>[\w|-]+)/$', UpdateView.as_view(), name="update")

Or, if there are lots of other character you want to add to the group, you could match anything except forward slashes with:

url(r'^edit/(?P<name>[^/]+)/$', UpdateView.as_view(), name="update")

Upvotes: 3

Related Questions