Following Django Tutorial (CRM)-Part5

This post is for myself to remember how to build Django project.
I did follow the tutorial from the JustDjango Learn website free tutorial.
And this is the fourth tutorial named Getting Started With Django.
I am not going over all the details and descriptions for each part. There are good explanations on video of the JustDjango Learn. So, visit their site and try their tutorials if you need more details. Also, the orders of this post and their video might be different because I put things first what I think should come first.

I am doing this on Windows 10 with just Windows PowerShell. Not using virtual machines at all.

1.make a create a new lead button

  • go to lead_list.html file
  • copy the below code and paste above h1 tag
<a href="/leads/create/">Create a new lead</a>
<hr />

2. add agent on detail page

  • go to lead_detail.html
  • copy the below code and paste below the age
<p>The agent responsible for this lead is : {{ lead.agent }}</p>

3. make model simpler

  • go to forms.py
  • import Lead from .models and copy the code below
class LeadModelForm(forms.ModelForm):
	class Meta:
		model = Lead
		fields = (
			'first_name',
			'last_name',
			'age',
			'agent',
		)
  • go to views.py
  • change LeadForm to LeadModelForm
  • delete all of form.is_valid and add form.save()

4. Lead Update View

  • on views.py create lead_update function by writing or copying below code
def lead_update(request, pk):
	lead = Lead.objects.get(id=pk)
	form = LeadModelForm(instance=lead)
	if request.method == "POST":
		form = LeadModelForm(request.POST, instance=lead)
		if form.is_valid():
			form.save()
			return redirect("/leads")
	context = {
		"form": form,
		"lead": lead
	}
	return render(request, "lead_update.html", context)
  • the above one is simpler and below screenshot has the code is expanded.
  • go to urls.py and add import and urlpatterns like below
  • create lead_update html file
  • copy the code below
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>test</title>
</head>
<body>
	<a href="/leads">Go back to leads</a>
	<hr />
	<h1>Update lead: {{ lead.first_name }} {{ lead.last_name }}</h1>
	<form method="post">
		{% csrf_token %}
		{{ form.as_p }}
		<button type="submit">Submit</button>
	</form>
</body>
</html>
  • save all the files created/edited and run server
  • go to http://localhost:8000/leads/1/update/
  • you will see the update page like below screenshot.

5. Lead Delete View

  • go to views.py
  • create lead_delete function
def lead_delete(request, pk):
	lead = Lead.objects.get(id=pk)
	lead.delete()
	return redirect("/leads")
  • go to urls.py
  • import lead_delete and add on urlpatterns.
  • go to lead_detail.html
  • add update and delete button
  • save the files and go to check on the browser.

Done for this post