The AccountList view has three main tasks. First, it should query the database to get a list of all accounts that belong to the user. Second, if that list of accounts is greater than 12 the view should paginate the list so that only 12 are shown at one time. Lastly, it should give the user the ability to search through their accounts. This functionality will be built over three lessons. The first task is to create a view that can render the list of all accounts.
/.../crmeasy/crmapp/accounts/views.py in your IDE. Edit it to look like the following.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
from django.views.generic import ListView from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .models import Account class AccountList(ListView): model = Account template_name = 'accounts/account_list.html' context_object_name = 'accounts' def get_queryset(self): account_list = Account.objects.filter(owner=self.request.user) return account_list @method_decorator(login_required) def dispatch(self, *args, **kwargs): return super(AccountList, self).dispatch(*args, **kwargs)
Line 1: This imports the CBV ListView. This is a pre-built CBV provided by Django that has all of the functionality to achieve the goals of this view.
Line 2: This is a tool that provides view security. Using it will ensure that only users who are authenticated have access to the account list page.
Line 3: This is used in conjunction with the login_decorator.
Line 5: This imports the previously created account model. This model will be used later in the view.
Line 7: This creates the AccountList view. It inherits functionality from the pre-built ListView CBV.
Line 8: This defines what model the view is based on. This view is based on the account model.
Line 9: This setting is used to specify the template used to display the account list.
Line 10: This setting gives the queried data a helpful name. This name can then be later used in templates.
Lines 12-14: This group of code overrides the default queryset method. By default, the view will gather all records from the model. The goal of this code is to override that behavior so that only the records for the current user are selected.
That's what is happening on line 13. It is assigning a Django queryset to the variable account_list. The queryset is being filtered by the current user, which can be accessed via self.request.user.
Lines 16-18: The task of this code is to protect the view so that only authenticated users can access it. This is done by applying login_required method decorator to the dispatch method.
Execute these commands to commit your changes in Git.
1 2 3 4 5
# add files (venv)$ git add . # commit files (venv)$ git commit -m "created account list view"