The
The

Reputation: 83

Get list of memberships for a user from the users model using generic listview

I want to create a view that shows a list of memberships fot a specific CustomUser. The view i have only shows a list of memberships for the logged in user. How can i achive this with generic.listview?

i want the list to show all the memberships for a specific user by passing the PK from CusomUser can anybody help me with this?

URL

path('<int:pk>/membership/', views.MemberShipIndex.as_view(), name='MemberShipIndex'),

View

class MemberShipIndex(generic.ListView):
    model = Membership
    template_name = 'members/membership_list.html'
    context_object_name = 'membership_list'

    def get_queryset(self):
        return self.model.objects.filter(CustomUser=self.request.user)

Upvotes: 1

Views: 73

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476709

You can filter on the pk parameter:

class MemberShipIndex(generic.ListView):
    model = Membership
    template_name = 'members/membership_list.html'
    context_object_name = 'membership_list'

    def get_queryset(self):
        return self.model.objects.filter(CustomUser_id=self.kwargs['pk'])

Note: normally the name of the fields in a Django model are written in snake_case, not PerlCase, so it should be: custom_user instead of CustomUser.

Upvotes: 1

Related Questions