Learn Django

Edit Contact - Modify View

Next, we can update the existing contact_cru() view so that it can be used for editing. This consists of adding the passing the uuid and account objects into the function, and giving the view a way to detect if

Open the /.../crmeasy/crmapp/contacts/views.py file in your IDE. Locate the contact_cru() view and update it as follows. Add the imports to the top of the file. Then update the view as it appears below.

New or modified lines are highlighted in yellow.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
from django.shortcuts import get_object_or_404

from crmapp.accounts.models import Account  


@login_required()
def contact_cru(request, uuid=None, account=None):

    if uuid:
        contact = get_object_or_404(Contact, uuid=uuid)
        if contact.owner != request.user:
            return HttpResponseForbidden()
    else:
        contact = Contact(owner=request.user)

    if request.POST:
        form = ContactForm(request.POST, instance=contact)
        if form.is_valid():
            # make sure the user owns the account
            account = form.cleaned_data['account']
            if account.owner != request.user:
                return HttpResponseForbidden()
            # save the data
            form.save()
            # return the user to the account detail view
            reverse_url = reverse(
                'crmapp.accounts.views.account_detail',
                args=(account.uuid,)
            )
            return HttpResponseRedirect(reverse_url)
        else:
            # if the form isn't valid, still fetch the account so it can be passed to the template
            account = form.cleaned_data['account']
    else:
        form = ContactForm(instance=contact)

    # this is used to fetch the account if it exists as a URL parameter
    if request.GET.get('account', ''):
        account = Account.objects.get(id=request.GET.get('account', ''))

    variables = {
        'form': form,
        'contact': contact,
        'account': account
    }

    template = 'contacts/contact_cru.html'

    return render(request, template, variables)

Commit Changes

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 "modified contact view to allow for editing"

Track your progress with a free account