Learn Django

View Account - Create View

Now that the URL conf is created we can build the account detail view. The job of this view is to query the database for a given account, and display its details on a template. The view is able to query the database using the account uuid in the URL.

Open /.../crmeasy/crmapp/accounts/views.py in your IDE. First, add the imports to the top of the file. Then, add theaccount_detail() function below the AccountList() class.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
from django.http import HttpResponseForbidden
from django.shortcuts import render

@login_required()
def account_detail(request, uuid):

    account = Account.objects.get(uuid=uuid)
    if account.owner != request.user:
            return HttpResponseForbidden()

    variables = {
        'account': account,
    }

    return render(request, 'accounts/account_detail.html', variables)

Code Review (only new/updated code reviewed)

Line 4: Decorating a FBV with the login_required() decorator ensures that only authenticated users can access this page.

Line 5: This defines the account_detail() FBV. This function takes two objects. The request object must be passed to every FBV; it is a requirement. The uuid object is passed to the view via the URL configuration. The uuid is a unique identifier for accounts. It will be used in this view to query the database for the correct account.

Line 7: This will query the Account model for a record matching the uuid passed to the view via the URL. The returned queryset will be assigned to the account variable.

Lines 8-9: This performs a quick check to see if the requested user is the account owner. If the user does own the account, then line 12 is not processed. If the user does not own the account, then line 12 is processed and the user is given a HTTP error 403.

Lines 11-13: This creates a dictionary of values and assigns it to the variables variable. This variable will be used in the return statement.

Line 15: This returns a web response to the user. It uses the render() shortcut to generate the correct page for the end user.

Track your progress with a free account