500 error on detail view if passing a string to an int lookup_field in the url.
For a /model/pk/$ route:
If pk is an int, and you try to hit:
/mymodel/banana
instead of:
/mymodel/123,
you'll get a ValueError: invalid literal for int() with base 10: 'banana'.
...
File "/Users/moose/.virtualenvs/djClothesPin/lib/python2.7/site-packages/rest_framework/views.py", line 336, in dispatch
response = handler(request, *args, **kwargs)
File "/Users/moose/.virtualenvs/djClothesPin/lib/python2.7/site-packages/rest_framework/mixins.py", line 100, in retrieve
self.object = self.get_object()
File "/Users/moose/.virtualenvs/djClothesPin/lib/python2.7/site-packages/rest_framework/generics.py", line 284, in get_object
obj = get_object_or_404(queryset, **filter_kwargs)
File "/Users/moose/.virtualenvs/djClothesPin/lib/python2.7/site-packages/django/shortcuts/__init__.py", line 113, in get_object_or_404
return queryset.get(*args, **kwargs)
...
I think before we get to the call to get_object_or_404 in generics.GenericAPIView.get_object, we need to do some validation based on lookup_field and return some sort of a 400 response.
Or just wrap get_object_or_404 in a try/except ValueError?
404 would be the correct response. Best approach would prob be to write a get_object_or_404 helper function that includes the try/catch and raises 404 on ValueError
I would say the problem isn't the framework itself but your urls.py file definitions. If you have something like:
urlpatterns = patterns(
'',
url(r'^books/$', views.BookList.as_view()),
url(r'^books/(?P<pk>[0-9]+)/$', views.BookDetail.as_view()),
)
Django itself will raise a 404 if pk doesn't match the regular expression [0-9]+. I don't know if this is a change needed to be done into REST framework.
I'm using the rest_framework router. The regex is accepting words, but the pk is obviously an int.
Oh, I got it wrong then, apologies.
It's a problem with the url patterns the router is generating.
2.2.6 generates:
^users/(?P<pk>[0-9]+)/$ [name='user-detail']
2.3.3 generates:
^users/(?P<pk>[^/]+)/$ [name='user-detail']
Edit:
I'm guessing 2.2.6 based on the tutorial site. I'm not actually sure what version of rest_framework it's running. It's using the router, but the release notes say routers came out in 2.3. The title says 2.2.6 though here http://restframework.herokuapp.com/snippets/.
The URL patterns are correct - pk's are not always AutoInteger fields. The lookup itself needs to guard against this case and raise 404, not 500.