New Contact - Create View
The second step on the journey to building a new contact form is to build the view. This is a pretty standard CRUD view. Upon receiving a request, the view will check to see if it's a POST request. If so it will extract the HTML form values and attempt to create a contact object.
If the request is not a POST, then the view will render a blank contact form.
Open the /.../crmeasy/crmapp/contacts/views.py
file in your IDE. First, add the imports to the top of the file. Then, add the contact_cru() FBV to the end of the file.
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
from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse from django.http import HttpResponseForbidden from .forms import ContactForm @login_required() def contact_cru(request): if request.POST: form = ContactForm(request.POST) 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 contact = form.save(commit=False) contact.owner = request.user contact.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: form = ContactForm() variables = { 'form': form, } template = 'contacts/contact_cru.html' return render(request, template, variables)
Code Review
Line 15: The new account form will contain a hidden input element. This field's value will be set to the account ID that the contact should be related to.
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 "created new account view"