1

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?

1 Answer 1

3

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")
Sign up to request clarification or add additional context in comments.

2 Comments

I suggest to simply add the | in the list of allowed characters : r'^edit/(?P<name>[\w|-]+)/$'
Thank you so much! This really helped me.

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.