Ishan Khare Ishan Khare - 1 year ago 101
Python Question

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download