Django Rest Framework - Could not resolve URL for hyperlinked relationship using view name "user-detail"
Solution 1:
Because it's a HyperlinkedModelSerializer
your serializer is trying to resolve the URL for the related User
on your Bottle
.
As you don't have the user detail view it can't do this. Hence the exception.
- Would not just registering the
UserViewSet
with the router solve your issue? - You could define the user field on your
BottleSerializer
to explicitly use theUserSerializer
rather than trying to resolve the URL. See the serializer docs on dealing with nested objects for that.
Solution 2:
I came across this error too and solved it as follows:
The reason is I forgot giving "**-detail" (view_name, e.g.: user-detail) a namespace. So, Django Rest Framework could not find that view.
There is one app in my project, suppose that my project name is myproject
, and the app name is myapp
.
There is two urls.py file, one is myproject/urls.py
and the other is myapp/urls.py
. I give the app a namespace in myproject/urls.py
, just like:
url(r'', include(myapp.urls, namespace="myapp")),
I registered the rest framework routers in myapp/urls.py
, and then got this error.
My solution was to provide url with namespace explicitly:
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="myapp:user-detail")
class Meta:
model = User
fields = ('url', 'username')
And it solved my problem.
Solution 3:
Maybe someone can have a look at this : http://www.django-rest-framework.org/api-guide/routers/
If using namespacing with hyperlinked serializers you'll also need to ensure that any view_name parameters on the serializers correctly reflect the namespace. For example:
urlpatterns = [
url(r'^forgot-password/$', ForgotPasswordFormView.as_view()),
url(r'^api/', include(router.urls, namespace='api')),
]
you'd need to include a parameter such as view_name='api:user-detail'
for serializer fields hyperlinked to the user detail view.
class UserSerializer(serializers.HyperlinkedModelSerializer):
url = serializers.HyperlinkedIdentityField(view_name="api:user-detail")
class Meta:
model = User
fields = ('url', 'username')