Django Rest Framework - Unable to resolve URLs for hyperlinks using view name "user-detail"

I am creating a project in the Django Rest Framework where users can enter their wine cellar. My ModelViewSets worked fine and suddenly I get this nasty error:

Unable to resolve URLs for hyperlinks using view name "user-detail". You may not have been able to include the associated model in your API or you might have incorrectly configured the lookup_field attribute in this field.

Tracking 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 user user model and a bottle model in models.py:

 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 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 detailed view of the user and I don’t see where this problem came from. Any ideas?

thank

+92
python django django-rest-framework user
Dec 12 '13 at 17:49
source share
15 answers

Since this is a HyperlinkedModelSerializer , your serializer is trying to resolve the associated User URL on your Bottle .
Since you do not have a detailed view of the user, he cannot do this. Hence the exception.

+81
Dec 12 '13 at 20:48
source share

I also came across this error and solved it as follows:

The reason is because I forgot to specify "** - detail" (view_name, for example: user-detail) namespace. Thus, the Django Rest Framework could not find this view.

There is one application in my project, suppose my project name is myproject and the application name is myapp .

There are two urls.py files, one is myproject/urls.py and the other is myapp/urls.py I provide the application namespace in myproject/urls.py , like:

 url(r'', include(myapp.urls, namespace="myapp")), 

I registered the rest of the infrastructure routers with myapp/urls.py and then got this error.

My solution was to explicitly specify the namespace URL:

 class UserSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="myapp:user-detail") class Meta: model = User fields = ('url', 'username') 

And he solved my problem.

+54
May 12 '16 at 6:02
source share

Maybe someone can look at this: http://www.django-rest-framework.org/api-guide/routers/

If you use namespacing with serializer hyperlinks, you also need to make sure that all view_name parameters on serializers correctly reflect the namespace. For example:

 urlpatterns = [ url(r'^forgot-password/$', ForgotPasswordFormView.as_view()), url(r'^api/', include(router.urls, namespace='api')), ] 

you need to include a parameter, such as view_name='api:user-detail' for serializer fields, hyperlinks to a detailed view of the user.

 class UserSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="api:user-detail") class Meta: model = User fields = ('url', 'username') 
+18
Jul 18 '16 at 14:55
source share

This code should also work.

 class BottleSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer() class Meta: model = Bottle fields = ('url', 'wine', 'user') 
+11
Dec 09 '14 at 19:20
source share

Another nasty bug causing this error has an unnecessary base_name definition in your urls.py. For example:

 router.register(r'{pathname}, views.{ViewName}ViewSet, base_name='pathname') 

This will result in the error noted above. Get this base_name and return to the working API. The code below will fix the error. Hurrah!

 router.register(r'{pathname}, views.{ViewName}ViewSet) 

However, you probably didn’t just randomly add base_name, you could do this because you defined a custom def get_queryset () to represent and therefore Django credentials added base_name. In this case, you need to explicitly define the "url" as HyperlinkedIdentityField for the serializer in question. Note that we are defining this HyperlinkedIdentityField on a SERIALIZER view that throws an error. If my error was “Failed to resolve URLs for hyperlinks using the view name“ Study-detail. ”You may not have been able to include the linked model in your API or you might have set the lookup_field attribute in this field.” I could fix this with the following code.

My ModelViewSet (custom get_queryset is why I had to add base_name to router.register () in the first place):

 class StudyViewSet(viewsets.ModelViewSet): serializer_class = StudySerializer '''custom get_queryset''' def get_queryset(self): queryset = Study.objects.all() return queryset 

Register my router for this ModelViewSet in urls.py:

 router.register(r'studies', views.StudyViewSet, base_name='studies') 

AND HERE WHERE MONEY! Then I could solve it like this:

 class StudySerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="studies-detail") class Meta: model = Study fields = ('url', 'name', 'active', 'created', 'time_zone', 'user', 'surveys') 

Yeah. You must explicitly define this HyperlinkedIdentityField for yourself in order for it to work. And you need to make sure that the view_name defined in HyperlinkedIdentityField is the same as you defined on base_name in urls.py with the addition of "-detail" after it.

+9
May 6 '17 at 5:15
source share

The same errors, but different reasons:

I define a user model of the user, nothing new field:

 from django.contrib.auth.models import (AbstractUser) class CustomUser(AbstractUser): """ custom user, reference below example https://github.com/jonathanchu/django-custom-user-example/blob/master/customuser/accounts/models.py # original User class has all I need # Just add __str__, not rewrite other field - id - username - password - email - is_active - date_joined - method, email_user """ def __str__(self): return self.username 

This is my view function:

 from rest_framework import permissions from rest_framework import viewsets from .models import (CustomUser) class UserViewSet(viewsets.ModelViewSet): permission_classes = (permissions.AllowAny,) serializer_class = UserSerializer def get_queryset(self): queryset = CustomUser.objects.filter(id=self.request.user.id) if self.request.user.is_superuser: queryset = CustomUser.objects.all() return queryset 

Since I did not give queryset directly in the UserViewSet , I have to set base_name when I register this view. This is my error message caused by urls.py file:

 from myapp.views import (UserViewSet) from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register(r'users', UserViewSet, base_name='customuser') # <--base_name needs to be 'customuser' instead of 'user' 

You need base_name the same as your model name - customuser .

+2
Sep 08 '17 at 6:51 on
source share

If you extend the GenericViewSet and ListModelMixin classes and have the same error when adding the url field as a list, because you do not define a detailed view. Make sure you extend the RetrieveModelMixin mix:

 class UserViewSet (mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet): 
+1
Dec 28 '17 at 22:19
source share

I came across the same error when I followed the DRF quick start guide http://www.django-rest-framework.org/tutorial/quickstart/ and then try to browse / users. I have done this setup many times, no problem.

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

The difference between this installation and others earlier was when I created a local database.

This time I ran

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

immediately after launch

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

Instead of the exact order specified in the manual.

I suspected that something was not created properly in the database. I did not care about my dev db, so I uninstalled it and ran the ./manage.py migrate command ./manage.py migrate , created the superuser, looked at the users / users and the error disappeared.

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

If you use sqlite and can test the changes to the new database, then it is worth a try before you start analyzing all your code.

0
Mar 06 '16 at 1:27
source share

Bottle = serializers.PrimaryKeyRelatedField (read_only = True)

read_only allows you to represent a field without having to associate it with another model representation.

0
Jul 13 '17 at 17:31
source share

I got this error on DRF 3.7.7 when the database value was empty (equal to '') in the database.

0
Apr 02 '18 at 0:59
source share

I ran into the same problem and solved it by adding generics.RetrieveAPIView as a base class to my set.

0
Jul 04 '18 at 19:50
source share

I got stuck in this error for almost 2 hours:

Incorrectly configured in / api_users / users / 1 / Failed to resolve the URL to link to the hyperlink using the view name "users-detail". You may not have been able to include the associated model in your API or you might have incorrectly configured the lookup_field attribute in this field.

When I finally found a solution, but I don’t understand why, my code looks like this:

 #models.py class Users(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, blank=False, null=False) email = models.EmailField(null=False, blank=False) class Meta: verbose_name = "Usuario" verbose_name_plural = "Usuarios" def __str__(self): return str(self.name) #serializers.py class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Users fields = ( 'id', 'url', 'name', 'email', 'description', 'active', 'age', 'some_date', 'timestamp', ) #views.py class UserViewSet(viewsets.ModelViewSet): queryset = Users.objects.all() serializer_class = UserSerializer #urls_api.py router = routers.DefaultRouter() router.register(r'users',UserViewSet, base_name='users') urlpatterns = [ url(r'^', include(router.urls)), ] 

but in my main urls this was:

 urlpatterns = [ url(r'^admin/', admin.site.urls), #api users url(r'^api_users/', include('usersApi.users_urls', namespace='api')), ] 

So finally, I solved the problem by erasing the namespace:

 urlpatterns = [ url(r'^admin/', admin.site.urls), #api users url(r'^api_users/', include('usersApi.users_urls')), ] 

And I finally solved my problem, so anyone can let me know why, the best.

0
Jul 30 '18 at 2:23
source share

If you omit the 'id' and 'url' fields in your serializer, you will not have any problems. You can access messages using an identifier that is returned in the json object anyway, which simplifies the implementation of your interface.

0
Dec 29 '18 at 18:41
source share

I had the same problem, I think you should check

get_absolute_url

input method value (** kwargs) of the title object method. and use the exact field name in lookup_field

0
Apr 05 '19 at 9:53 on
source share

I encountered this error after adding a namespace to my URL

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

and adding app_name to my urls.py

I solved this problem by specifying NamespaceVersioning for my api Framework to relax in the settings.py of my project

 REST_FRAMEWORK = { 'DEFAULT_VERSIONING_CLASS':'rest_framework.versioning.NamespaceVersioning'} 
0
Sep 03 '19 at 12:17
source share



All Articles