1
votes

I am trying to use an alternative id besides the pk for a hyperlink, however I am getting an error:

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

During handling of the above exception (Reverse for 'foos-detail' with arguments '()' and keyword arguments '{'pk': 27}' not found. 2 pattern(s) tried: ['api/foos/(?P[^/.]+)\.(?P[a-z0-9]+)/?$', 'api/foos/(?P[^/.]+)/$']), another exception occurred:

Serializer:

class FooSerializer(serializers.HyperlinkedModelSerializer):
    url = serializers.HyperlinkedIdentityField(view_name='foos-detail', format='html')
class Meta:
    model = Foo
    fields = ('url', 'alt_id', 'created', 'modified', 'name')

ViewSet:

class FooViewSet(viewsets.ModelViewSet):
    queryset = Foo.objects.all()
    serializer_class = FooSerializer
    lookup_field = 'alt_id'

Urls:

router = DefaultRouter()
router.register(r'foos', FooViewSet, 'foos')
urlpatterns = [
    url(r'^', include(router.urls)),
    url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

Edit: This is definitely a result of trying to use a lookup_field. Deleting the lookup_field in the viewset results in hyperlinks being displayed correctly for the pk.

2

2 Answers

0
votes

You are missing the namespace in the view_name:

url = serializers.HyperlinkedIdentityField(view_name='rest_framework :foos-detail', format='html')
0
votes

It cost me hours, and I finally made it work. After you make the identification right on class Meta, try these:

  1. name your 'field-list' or 'field-detail' following common habit

  2. add namespace before them for restframework to work well, like

    @api_view(['GET'])
    def api_root(request, format=None):
        return Response({
            'users':reverse('snippets:user-list', request=request, format=format),
            'snippets':reverse('snippets:snippet-list',request=request, format=format)
    })
    
  3. make var url clear when you use serializers.HyperlinkedModelSerializer

    url = serializers.HyperlinkedIdentityField(view_name="snippets:user-detail")