Ishan Khare
Ishan Khare

Reputation: 1767

Django 'Request' object has no attribute 'user_id'

In my urls.py I have:

url(r'^dashboard/users/(?P<user_id>[0-9]+)/products/$', views.UserProductsList.as_view())

in views.py

class UserProductsList(generics.ListCreateAPIView):
     def get_queryset(self):
         if self.request.user_id:
             return UserProducts.objects.filter(user_id=self.request.user_id).order_by('id')
         else:
             return UserProducts.objects.all().order_by('id')

I want to be able to access my api as such:

http://localhost:8000/dashboard/users/10/products

should list all products of that user, and

http://localhost:8000/dashboard/users/10/products/1

should return product_id 1 of user_id 10

How can I implement this flow.

Note: I'm using Django rest framework in this setup

Upvotes: 1

Views: 5726

Answers (2)

Abin Abraham
Abin Abraham

Reputation: 517

Please update your code like this..

class UserProductsList(generics.ListCreateAPIView):
 def get_queryset(self):
     if self.request.user.id:
         return 

Or

class UserProductsList(generics.ListCreateAPIView):
 def get_queryset(self):
     if self.kwargs['user_id']:
         return 

Upvotes: 1

itzMEonTV
itzMEonTV

Reputation: 20369

You can do

class UserProductsList(generics.ListCreateAPIView):
     def get_queryset(self):
         if self.kwargs['user_id']:
             return UserProducts.objects.filter(user_id=self.kwargs['user_id']).order_by('id')
         else:
             return UserProducts.objects.all().order_by('id')

Refer doc

Upvotes: 4

Related Questions