简体   繁体   中英

Could not resolve URL for hyperlinked relationship with Django REST Framework

I am building a project in Django Rest Framework to interact with my React app, enabling users to signup and create a profile.

However, when I run python manage.py runserver and click on the url appearing on API Root Page I get the following error message:

ImproperlyConfigured at /profiles/
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.

Here is my models.py code:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    name = models.CharField(max_length=100, blank=True)
    location = models.CharField(max_length=100, blank=True)
    email = models.EmailField(max_length=150)
    signup_confirmation = models.BooleanField(default=False)

    def __str__(self):
        return self.user.username

@receiver(post_save, sender=User)
def update_profile_signal(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)
    instance.profile.save()

My serializers.py:

from rest_framework import serializers
from .models import Profile

class ProfileSerializer(serializers.HyperlinkedModelSerializer):
    class Meta:
        model = Profile
        fields = ('user', 'name', 'location', 'email', 'signup_confirmation')

urls.py:

from django.urls import path, include
from rest_framework import routers
from .import views

router = routers.DefaultRouter()
router.register(r'profiles', views.ProfileViewSet)

urlpatterns = [
    path('', include(router.urls)),
    path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]

and views.py

from rest_framework import viewsets

from .serializers import ProfileSerializer
from .models import Profile
from .forms import SignUpForm
from .tokens import account_activation_token

class ProfileViewSet(viewsets.ModelViewSet):
    queryset = Profile.objects.all().order_by('name')
    serializer_class = ProfileSerializer

Any idea of why I am getting this error

You are inheriting HyperlinkedModelSerializer in ProfileSerializer , and ProfileSerializer has a user field configured inside Meta . That means that it has to search for reverse URL of user-detail view (with some pk arg). But you have no view associated with this view name, so you get ImproperlyConfigured

Upd:

The simplest fix will be inheriting from ModelSerializer instead of HyperlinkedModelSerializer . Differences are

  1. HyperlinkedModelSerializer does not include id field by default
  2. HyperlinkedModelSerializer includes url field, that points at url of serialized instance
  3. Relationships use HyperlinkedRelatedField , instead of PrimaryKeyRelatedField .

The main reason for you to switch over to ModelSerializer is that you don't need to configure view names (eg creating viewsets) for every related model.

You can also read the docs for more details

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM