[Django]-Django.core.exceptions.ImproperlyConfigured: Could not resolve URL for hyperlinked relationship using view name "user-detail"

2๐Ÿ‘

โœ…

I eventually fixed my second exception by printing the serializer in the Django shell/python interactive console. The result I got was this:

>>> from snippets.serializers import UserSerializer
>>> print(UserSerializer())
UserSerializer():
    url = HyperlinkedIdentityField(view_name='user-detail')
    id = IntegerField(label='ID', read_only=True)
    username = CharField(help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, validators=[<django.contrib.auth.validators.UnicodeUsernameValidator object>, <UniqueValidator(queryset=User.objects.all())>])
    snippets = HyperlinkedRelatedField(lookup_field='id', many=True, read_only=True, view_name='snippet-detail')

It turns out that to change <pk> to <id> in urlspatterns, you need to add url = HyperlinkedIdentityField(view_name='user-detail', lookup_field='id') in the UserSerializer class.

4๐Ÿ‘

For anyone else coming across this question after following the the tutorial, here is the answer.

Change these lines

router.register(r'snippets', views.SnippetViewSet,basename="snippets")
router.register(r'users', views.UserViewSet,basename="users")

To these (note the singular basenames)

router.register(r'snippets', views.SnippetViewSet,basename="snippet")
router.register(r'users', views.UserViewSet,basename="user")

If you follow it exactly as the tutorial exactly as written, it generates these router URLs (notice snippets-details). This is what causes the error

<URLPattern '^snippets\.(?P<format>[a-z0-9]+)/?$' [name='snippets-list']>
<URLPattern '^snippets/(?P<pk>[^/.]+)/$' [name='snippets-detail']>
<URLPattern '^snippets/(?P<pk>[^/.]+)\.(?P<format>[a-z0-9]+)/?$' [name='snippets-detail']>
<URLPattern '^snippets/(?P<pk>[^/.]+)/highlight/$' [name='snippets-highlight']>
<URLPattern '^snippets/(?P<pk>[^/.]+)/highlight\.(?P<format>[a-z0-9]+)/?$' [name='snippets-highlight']>

0๐Ÿ‘

I just had the same problem and I found, that the HyperlinkedIdentityField wants to insert some placeholder into your URL. But I had used URLs which did not require any placeholders to be set. A ListCreateAPIView to be precise:

url(
    r'^users/$',                  #<-- takes no params
    views.UserListView.as_view(), #<-- just prints a list 
    name="user-list"              #<-- HyperlinkedIdentityField pointing 
),                                #     here complained bitterly.

Leave a comment