peterpeter5
peterpeter5

Reputation: 83

Django REST - How do I correctly configure URLs lookup_field?

I've made a few django projects and am now experimenting with the rest framework. I'm trying to configure my urls such that url /testuser/ will take you to the profile page of user with username 'testuser'. Pretty simple task that I can manage in regular django using slug_field but I guess I'm not quite understanding how to correctly configure REST urls. Any help appreciated. Code below.

FYI, as you will see below, I am using a CustomUser model, linked to a Profile model by OneToOneField. The username is stored in the CustomUser model. However, the profile page will be populated using ProfileSerializer.

I believe the issue might be the way I am accessing the 'username' from the related model, CustomUser - but I could be wrong (likely, lol). Anyone have any idea?

My current code throws the error:

Expected view ProfileView to be called with a URL keyword argument named "username". Fix your URL conf, or set the .lookup_field attribute on the view correctly.

users.models

class CustomUser(AbstractBaseUser):
    username = models.CharField(
        verbose_name='username',
        max_length=40,
        unique=True,
    )
    ...

profiles.models

class Profile(models.Model):
    user = models.OneToOneField(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE,
        related_name='profile'
    )
    ...

profiles.serializers

class ProfileSerializer(serializers.ModelSerializer):
    username = serializers.CharField(read_only=True, source="user.username")

    class Meta:
        fields = ('username', 'display_name', 'profile_pic',
                  'bio', 'following', 'modified', 'est', )
        model = Profile
        lookup_field = 'username'

profiles.views

class ProfileView(generics.RetrieveUpdateAPIView):
    queryset = Profile.objects.all()
    serializer_class = ProfileSerializer
    lookup_field = 'username'

profiles.urls

urlpatterns = [
    path('<str:slug>/', PostDetail.as_view(), name='self_profile'),
]

Thanks for your help.

Upvotes: 1

Views: 694

Answers (1)

GwynBleidD
GwynBleidD

Reputation: 20539

Your view is expecting username URL parameter, but it receives slug. You can either change your URL to pass on username instead of slug, or set lookup_url_kwarg to slug on your view to fix that situation.

Upvotes: 1

Related Questions