How to HyperlinkedRelatedField into a model from different app?

Viewed 28

bellow is urls.py of users app.

from django.urls import path

from . import views


app_name = 'users'

urlpatterns = [
    path('', views.UserList.as_view(), name='user-list'),
    path('<int:id>/', views.UserDetail.as_view(), name='user-detail'),
]

url conf of snippets app:

from django.urls import path

from . import views


app_name = 'snippets'

urlpatterns = [
    path('', views.SnippetList.as_view(), name='snippet-list'),
    path('<int:pk>/', views.SnippetDetail.as_view(), name='snippet-detail'),
    path('<int:pk>/highlight/', views.SnippetHighlight.as_view(), name='snippet-highlight'),
]

and here's SnippetSerializer

from rest_framework import serializers

from . import models


class SnippetSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = models.Snippet
        fields = ['id', 'owner', 'title', 'code', 'highlight', 'linenos', 'language', 'style']

    highlight = serializers.HyperlinkedIdentityField(view_name='snippets:snippet-highlight', format='html')
    owner = serializers.HyperlinkedRelatedField(
        read_only=True,
        view_name='users:user-detail'
    )

The error I got

ImproperlyConfigured at /snippets/ Could not resolve URL for hyperlinked relationship using view name "users:user-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field.

1 Answers

My mistake was that I specified id instead of pk in url pattern of users app. Such things make me feel frustrated.

Related