Reputation: 738
I am messing around with a backend Django API tutorial (Django 2.1) and I am having trouble pulling 'profile' information via Postman. My assumption is that I am not correctly stating my url in my urls.py.
Here is my project urls.py:
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('conduit.apps.authentication.urls'), name='authentication'),
path('api/v1/', include('conduit.apps.profiles.urls'), name='profiles')
]
Here is my profiles.urls.py:
from .views import ProfileRetrieveAPIView
urlpatterns = [
path('profiles/<username:username>/', ProfileRetrieveAPIView.as_view())
]
I think my issue has to do with how I am implementing / to the end of my path. My only other relevant experience with this kind of mechanism was on prior projects where I was using something like this for unique blog post url routing (which I have done successfully):
".../<slug:slug>/"
Now, here is my relevant class-based view for the above url:
class ProfileRetrieveAPIView(RetrieveAPIView):
permission_classes = (AllowAny,)
renderer_classes = (ProfileJSONRenderer,)
serializer_class = ProfileSerializer
def retrieve(self, request, username, *args, **kwargs):
try:
profile = Profile.objects.select_related('user').get(
user__username=username
)
except Profile.DoesNotExist:
raise ProfileDoesNotExist
serializer = self.serializer_class(profile)
return Response(serializer.data, status=status.HTTP_200_OK)
You can see in my retrieve function, I am working with a username attribute. This is what I think I am trying to match up with my url path. I am guessing that I am probably not understanding how to correctly associate the url path variable (that terminology doesn't sound right) with my view. Thanks!
Also - the tutorial I am following is having me make a GET request in postman. The collection I downloaded as part of the tutorial has the following url in populated by default:
http://127.0.0.1:8000/api/v1/profiles/celeb_harry
Where is the 'celeb_' prefacing my username ('harry') coming from. I am not seeing that in any of my .py files (renderers, serializers, views, urls, etc)
Upvotes: 0
Views: 725
Reputation: 51998
You need to set lookup_field
in you View. For example:
class ProfileRetrieveAPIView(RetrieveAPIView):
lookup_field = 'username'
path('profiles/<username>/', ProfileRetrieveAPIView.as_view())
What happens is that, inside get_object
method of the view, based on lookup_field
, a get_object_or_404
is executed. Please see the implementation in here for understanding how RetrieveAPIView works.
Upvotes: 1