[Answer]-Restricting access to Django generic views

1👍

You could use the helper function get_object_or_404() to first get the account object if you want to have a 404 error.

Like this:

def get_queryset(self):
    account_id = self.kwargs['account_id']

    # raise 404 if no account is found for the current user
    account = get_object_or_404(Account, pk=account_id, user=self.request.user)

    queryset = Transaction.objects.filter(account=account)
    return queryset

For your second thing you mentioned, you could either make a new view, or just check if 'account_id' was in the url, and reuse your current view. You will need a new url either way.

urls.py:

url(r'^(?P<account_id>\d+)/$', views.IndexView.as_view(), name='index'),
url(r'^$', views.IndexView.as_view(), name='index'), 

modify your get_queryset() again for the case where no account id is in the url:

def get_queryset(self):
    # account_id will be None if the second url was the one that matched.
    account_id = self.kwargs.get('account_id', None) 

    if account_id:
        # raise 404 if no account is found for the current user
        account = get_object_or_404(Account, pk=account_id, user=self.request.user)

        queryset = Transaction.objects.filter(account=account)
    else:
        # we're going to show all transactions for the user, rather than a specific account
        queryset = Transaction.objects.filter(account__user=self.request.user)

    return queryset

Leave a comment