Django Rest Framework - Could not resolve URL for

2020-01-26 03:24发布

I am building a project in Django Rest Framework where users can login to view their wine cellar. My ModelViewSets were working just fine and all of a sudden I get this frustrating error:

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

The traceback shows:

    [12/Dec/2013 18:35:29] "GET /bottles/ HTTP/1.1" 500 76677
Internal Server Error: /bottles/
Traceback (most recent call last):
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/django/core/handlers/base.py", line 114, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/viewsets.py", line 78, in view
    return self.dispatch(request, *args, **kwargs)
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/django/views/decorators/csrf.py", line 57, in wrapped_view
    return view_func(*args, **kwargs)
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/views.py", line 399, in dispatch
    response = self.handle_exception(exc)
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/views.py", line 396, in dispatch
    response = handler(request, *args, **kwargs)
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/mixins.py", line 96, in list
    return Response(serializer.data)
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/serializers.py", line 535, in data
    self._data = [self.to_native(item) for item in obj]
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/serializers.py", line 325, in to_native
    value = field.field_to_native(obj, field_name)
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/relations.py", line 153, in field_to_native
    return self.to_native(value)
  File "/Users/bpipat/.virtualenvs/usertest2/lib/python2.7/site-packages/rest_framework/relations.py", line 452, in to_native
    raise Exception(msg % view_name)
Exception: Could not resolve URL for hyperlinked relationship using view 
name "user-detail". You may have failed to include the related model in 
your API, or incorrectly configured the `lookup_field` attribute on this 
field.

I have a custom email user model and the bottle model in models.py is:

class Bottle(models.Model):    
      wine = models.ForeignKey(Wine, null=False)
      user = models.ForeignKey(User, null=False, related_name='bottles')

My serializers:

class BottleSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Bottle
        fields = ('url', 'wine', 'user')

class UserSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name', 'password', 'is_superuser')

My views:

class BottleViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows bottles to be viewed or edited.
    """
    queryset = Bottle.objects.all()
    serializer_class = BottleSerializer

class UserViewSet(ListCreateAPIView):
    """
    API endpoint that allows users to be viewed or edited.
    """
    queryset = User.objects.all()
    serializer_class = UserSerializer

and finally the url:

router = routers.DefaultRouter()
router.register(r'bottles', views.BottleViewSet, base_name='bottles')

urlpatterns = patterns('',
    url(r'^', include(router.urls)),
    # ...

I don't have a user detail view and I don't see where this issue could come from. Any ideas?

Thanks

17条回答
冷血范
2楼-- · 2020-01-26 03:52

I ran into this error after adding namespace to my url

 url('api/v2/', include('api.urls', namespace='v2')),

and adding app_name to my urls.py

I resolved this by specifying NamespaceVersioning for my rest framework api in settings.py of my project

REST_FRAMEWORK = {
    'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.NamespaceVersioning'}
查看更多
▲ chillily
3楼-- · 2020-01-26 03:54

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.

查看更多
Deceive 欺骗
4楼-- · 2020-01-26 03:55

Bottle = serializers.PrimaryKeyRelatedField(read_only=True)

read_only allows you to represent the field without having to link it to another view of the model.

查看更多
我想做一个坏孩纸
5楼-- · 2020-01-26 03:56

I ran into the same error while I was following the DRF quickstart guide http://www.django-rest-framework.org/tutorial/quickstart/ and then attempting to browse to /users. I've done this setup many times before without problems.

My solution was not in the code but in replacing the database.

The difference between this install and the others before was when I created the local database.

This time I ran my

./manage.py migrate
./manage.py createsuperuser

immediately after running

virtualenv venv
. venv/bin/activate
pip install django
pip install djangorestframework

Instead of the exact order listed in the guide.

I suspected something wasn't properly created in the DB. I didn't care about my dev db so I deleted it and ran the ./manage.py migrate command once more, created a super user, browsed to /users and the error was gone.

Something was problematic with the order of operations in which I configured DRF and the db.

If you are using sqlite and are able to test changing to a fresh DB then it's worth an attempt before you go dissecting all of your code.

查看更多
smile是对你的礼貌
6楼-- · 2020-01-26 03:56

It appears that HyperlinkedModelSerializer do not agree with having a path namespace. In my application I made two changes.

# rootapp/urls.py
urlpatterns = [
    # path('api/', include('izzi.api.urls', namespace='api'))
    path('api/', include('izzi.api.urls')) # removed namespace
]

In the imported urls file

# app/urls.py
app_name = 'api' // removed the app_name

Hope this helps.

查看更多
成全新的幸福
7楼-- · 2020-01-26 03:58

If you omit the fields 'id' and 'url' from your serializer you won't have any problem. You can access to the posts by using the id that is returned in the json object anyways, which it makes it even easier to implement your frontend.

查看更多
登录 后发表回答