Skip to content

Commit

Permalink
Merge pull request #321 from uchicago-cs/apis/user-detail-slugs
Browse files Browse the repository at this point in the history
Added ability for `username` to act as identifier for API user detail endpoint in addition to primary key (`/api/users/<userID>` OR `/api/users/<username>`)
  • Loading branch information
majorsylvie authored Dec 4, 2023
2 parents d8644b4 + 0546104 commit eb2f8e2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
2 changes: 1 addition & 1 deletion src/chigame/api/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
path("lobbies/<int:pk>/", views.LobbyDetailView.as_view(), name="api-lobby-detail"),
# USER API URLS
path("users/", views.UserListView.as_view(), name="api-user-list"),
path("users/<int:pk>/", views.UserDetailView.as_view(), name="api-user-detail"),
path("users/<slug:slug>/", views.UserDetailView.as_view(), name="api-user-detail"),
path("users/<int:pk>/friends/", views.UserFriendsAPIView.as_view(), name="api-user-friends"),
# CHAT API URLS
path("tournaments/chat/", views.MessageView.as_view(), name="api-chat-list"),
Expand Down
14 changes: 13 additions & 1 deletion src/chigame/api/views.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# from django.shortcuts import render
from django.shortcuts import get_object_or_404
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import generics, status
from rest_framework.pagination import PageNumberPagination
Expand Down Expand Up @@ -35,7 +36,7 @@ class UserFriendsAPIView(generics.RetrieveAPIView):

def get_queryset(self):
user_id = self.kwargs["pk"]
user_profile = UserProfile.objects.get(user=user_id)
user_profile = get_object_or_404(UserProfile, user=user_id)
return user_profile.friends.all()


Expand All @@ -60,6 +61,17 @@ class UserListView(generics.ListCreateAPIView):
class UserDetailView(generics.RetrieveUpdateDestroyAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
lookup_field = "slug"

def get_object(self):
lookup_value = self.kwargs.get(self.lookup_field)

# If the lookup_value is an integer, use the id field
if lookup_value.isdigit():
return get_object_or_404(User, pk=lookup_value)
else:
# Otherwise, use the slug field
return get_object_or_404(User, username=lookup_value)


class MessageView(generics.CreateAPIView):
Expand Down

0 comments on commit eb2f8e2

Please sign in to comment.