Introduction:
The Contact Manager CRUD app is a common project for software developers to gain hands-on experience with web application development. In this step-by-step guide, we will explore how to create a Contact Manager app using Django, a powerful Python web framework, and MySQL, a popular relational database management system. By following this guide, you will learn how to set up the project, implement CRUD operations, and ensure data security. Let's dive in!
Prerequisites:
- Basic knowledge of Python and Django.
- Understanding of web development concepts such as HTML, CSS, and JavaScript.
- Python and Django installed on your development machine.
- MySQL Server installed and running.
Step 1: Project Setup
- Install Django by running the following command in your terminal:
pip install Django
2.Create a new Django project by running the following command:
django-admin startproject contact_manager
3.Navigate to the project directory:
cd contact_manager
4.Set up the database configuration in the project's settings file (settings.py). Update the DATABASES setting with the following configuration:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'your_database_name',
'USER': 'your_database_user',
'PASSWORD': 'your_database_password',
'HOST': 'localhost',
'PORT': '3306',
}
}
5.Add the 'contacts' app to the project's INSTALLED_APPS list in the settings.py file, follow these steps:
- Open the settings.py file located in your Django project's root directory.
- Locate the INSTALLED_APPS list in the settings.py file. It should look something like this:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'contacts' # Add this line
]
By adding 'contacts' to the INSTALLED_APPS list, you are instructing Django to include the 'contacts' app in the project and make it available for use.
Step 2: Create the Contact App
- Generate a new Django app for managing contacts by running the following command:
python manage.py startapp contacts
2.Define the Contact model in the contacts/models.py file:
from django.db import models
# Create your models here.
class Contact(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
phone = models.CharField(max_length=15)
def __str__(self):
return self.name
3.Create the database tables by running the following command to generate the migrations:
python manage.py makemigrations contacts
Then, apply the migrations to create the tables in the database:
python manage.py migrate
Step 3: Implement the CRUD Functionality
1.Define the views:
In the views.py file of the 'contacts' app, define the views for CRUD operations:
from django.shortcuts import render, get_object_or_404, redirect
from .models import Contact
def contact_list(request):
contacts = Contact.objects.all()
return render(request, 'contacts/contact_list.html', {'contacts': contacts})
def contact_create(request):
if request.method == 'POST':
contact = Contact(name=request.POST['name'], email=request.POST['email'], phone=request.POST['phone'])
contact.save()
return redirect('contact_list')
return render(request, 'contacts/contact_create.html')
def contact_update(request, pk):
contact = get_object_or_404(Contact, pk=pk)
if request.method == 'POST':
contact.name = request.POST['name']
contact.email = request.POST['email']
contact.phone = request.POST['phone']
contact.save()
return redirect('contact_list')
return render(request, 'contacts/contact_update.html', {'contact': contact})
def contact_delete(request, pk):
contact = get_object_or_404(Contact, pk=pk)
if request.method == 'POST':
contact.delete()
return redirect('contact_list')
return render(request, 'contacts/contact_delete.html', {'contact': contact})
2.Define the URLs:
In the urls.py file of the Django project, define the URL patterns for the 'contacts' app:
from django.urls import path
from contacts.views import contact_list, contact_create, contact_update, contact_delete
urlpatterns = [
path('', contact_list, name='contact_list'),
path('create/', contact_create, name='contact_create'),
path('update/<int:pk>/', contact_update, name='contact_update'),
path('delete/<int:pk>/', contact_delete, name='contact_delete'),
]
3.Create templates:
- Create a directory named templates in the 'contacts' app directory.
- Inside the templates directory, create a contacts directory.
- Create the following HTML templates inside the contacts directory: - contact_list.html: The template for displaying the contact list. -contact_create.html: The template for creating a new contact. -contact_update.html: The template for updating a contact. -contact_delete.html: The template for deleting a contact.
4.Create base.html file in placed inside the templates directory of your Django project. By default, Django looks for templates in the templates directory within each app and in the project's root directory.
Here's the recommended directory structure for placing the base.html file:
your_project/
├── your_project/
│ ├── settings.py
│ ├── urls.py
│ └── ...
├── contacts/
│ ├── templates/
│ │ └── base.html <-- Place base.html here
│ ├── models.py
│ ├── views.py
│ └── ...
├── manage.py
└── ...
Make sure to include the necessary Bootstrap and jQuery CDN links in your base HTML template (base.html).
Set up URL patterns in the contacts/urls.py file to map the views to appropriate URLs:
In the above structure, you can create a templates directory inside the contacts app directory if it doesn't already exist. Then, place the base.html file inside the templates directory.
Make sure that your Django project's TEMPLATES **setting in **settings.py is configured to include the app_directories.Loader so that Django can find the templates. By default, this setting is included in the TEMPLATES list. It should look something like this:
TEMPLATES = [
{
...
'BACKEND':'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
...
},
]
Once you have placed the base.html file in the appropriate location, it will be available for other templates to extend or include using Django's template inheritance mechanism.
5.Create other templates inside the contacts folder inside templates folder
Here are the HTML templates with the code:
1.Contact list Template (contact_list.html)
{% extends 'base.html' %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
<h2>Contact List</h2>
<a href="{% url 'contact_create' %}" class="btn btn-primary btn-sm">Create Contact</a>
</div>
<table class="table">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for contact in contacts %}
<tr>
<td>{{ contact.name }}</td>
<td>{{ contact.email }}</td>
<td>{{ contact.phone }}</td>
<td>
<a href="{% url 'contact_update' contact.id %}" class="btn btn-primary btn-sm">Edit</a>
<a href="{% url 'contact_delete' contact.id %}" class="btn btn-danger btn-delete btn-sm">Delete</a>
</td>
</tr>
{% empty %}
<tr>
<td colspan="4">No contacts available.</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
$(document).ready(function() {
$('.btn-delete').click(function(e) {
e.preventDefault();
if (confirm('Are you sure you want to delete this contact?')) {
window.location.href = $(this).attr('href');
}
});
});
</script>
{% endblock %}
2.Contact Creation Template (contact_create.html)
{% extends 'base.html' %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
<h2>Create Contact</h2>
<a href="{% url 'contact_list' %}" class="btn btn-danger btn-sm">Back</a>
</div>
<form method="post" action="{% url 'contact_create' %}">
{% csrf_token %}
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control form-control-sm" id="name" name="name" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control form-control-sm" id="email" name="email" required>
</div>
<div class="form-group mb-2">
<label for="phone">Phone:</label>
<input type="tel" class="form-control form-control-sm" id="phone" name="phone" required>
</div>
<button type="submit" class="btn btn-primary btn-sm">Create</button>
</form>
{% endblock %}
3.Contact Update Template (contact_update.html)
{% extends 'base.html' %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
<h2>Update Contact</h2>
<a href="{% url 'contact_list' %}" class="btn btn-danger btn-sm">Back</a>
</div>
<form method="post" action="{% url 'contact_update' contact.id %}">
{% csrf_token %}
<div class="form-group">
<label for="name">Name:</label>
<input type="text" class="form-control form-control-sm" id="name" name="name" value="{{ contact.name }}" required>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" class="form-control form-control-sm" id="email" name="email" value="{{ contact.email }}" required>
</div>
<div class="form-group">
<label for="phone">Phone:</label>
<input type="tel" class="form-control form-control-sm" id="phone" name="phone" value="{{ contact.phone }}" required>
</div>
<button type="submit" class="btn btn-primary btn-sm">Update</button>
</form>
{% endblock %}
4.Contact Creation Template (contact_delete.html)
{% extends 'base.html' %}
{% block content %}
<div class="d-flex justify-content-between align-items-center mb-3">
<h2>Delete Contact</h2>
<a href="{% url 'contact_list' %}" class="btn btn-danger btn-sm">Back</a>
</div>
<p>Are you sure you want to delete the contact: {{ contact.name }}?</p>
<form method="post" action="{% url 'contact_delete' contact.id %}">
{% csrf_token %}
<button type="submit" class="btn btn-danger btn-sm">Delete</button>
</form>
{% endblock %}
That's it! You have now set up the database, defined the models, views, URLs, and templates for your contact management app with Django and MySQL. Remember to run the Django development server using python manage.py runserver and access the app in your browser to interact with the CRUD functionality.
Step 4: Run your Django application
To run your Django application, you can follow these steps:
1.Open a terminal or command prompt.
2.Navigate to the root directory of your Django project using the cd
command. For example, if your project is located in /path/to/your_project
, you would run:
cd /path/to/your_project
3.Activate your virtual environment if you are using one. If you are not using a virtual environment, you can skip this step.
4.Once you are in the project's root directory, run the following command to start the development server:
python manage.py runserver
This command runs the Django development server and starts your application.
5.You should see output similar to the following:
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
This indicates that your Django application is running locally.
6.Open a web browser and visit http://127.0.0.1:8000/
or http://localhost:8000/
. You should see your contact management application's homepage.
From there, you can navigate to different views such as the contact list, create contact, update contact, and delete contact.
7.To stop the development server, go back to the terminal or command prompt where the server is running and press Ctrl + C
to stop the server.
Conclusion:
Congratulations! You have successfully run your Django application. You can continue developing and testing your application by making changes to the code and restarting the development server as needed.
For any inquiries, please leave a comment
Top comments (0)