Django
with MySQL
Django with
MySQL Documentation
1. Overview
Django
is a powerful web framework for building web applications in Python. It
provides a high-level ORM to interact with various databases, including MySQL.
This documentation will guide you through integrating Django with MySQL and
provide a complete example application.
2. Pre-requisites
Before
proceeding, ensure you have the following:
- Python
(version 3.x)
- MySQL
Server
installed
- Django
(latest version)
- A
MySQL client (optional, e.g., MySQL Workbench)
3. Setting Up the Environment
3.1 Installing MySQL
- Download
and install MySQL from the official MySQL website.
- Follow
the installation instructions for your operating system.
- Create
a new database for your Django project using the MySQL command line or a
GUI.
Sql
CREATE
DATABASE mydatabase;
3.2 Installing Django
You
can install Django using pip:
Bash
pip
install django
3.3 Installing the MySQL Python Driver
To enable Django to interact with
MySQL, install the mysqlclient
driver:
Bash
pip
install mysqlclient
If
you encounter issues, ensure you have the MySQL development libraries
installed. On Ubuntu, for instance, use:
Bash
sudo
apt-get install libmysqlclient-dev
4. Creating a Django Project
Create
a new Django project:
Bash
django-admin
startproject myproject
cd
myproject
5. Configuring MySQL Database Settings
Open
myproject/settings.py
and update the DATABASES
configuration:
Python
DATABASES
= {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase', # Your database name
'USER': 'myuser', # Your MySQL username
'PASSWORD': 'mypassword', # Your MySQL password
'HOST': 'localhost', # Database host
'PORT': '3306', # Default MySQL port
}
}
6. Creating a Django App
Inside
your project directory, create a new app:
Bash
python
manage.py startapp myapp
7. Defining Models
Open
myapp/models.py
and define a simple model, for example, a Product:
Python
from
django.db import models
class
Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.DecimalField(max_digits=10,
decimal_places=2)
def __str__(self):
return self.name
8. Using the Admin Interface
To
manage products through the admin interface, register your model in myapp/admin.py:
Python
from
django.contrib import admin
from
.models import Product
admin.site.register(Product)
9. Querying the Database
After
registering the model, you can run migrations to create the necessary tables:
Bash
python
manage.py makemigrations myapp
python
manage.py migrate
Create
a superuser to access the admin interface:
Bash
python
manage.py createsuperuser
Start
the development server:
Bash
python
manage.py runserver
Access
the admin interface at http://127.0.0.1:8000/admin,
log in with your superuser credentials, and add products.
Example of Querying
You
can interact with your database through the Django shell. Open the shell with:
Bash
python
manage.py shell
Then,
run the following commands:
Python
from
myapp.models import Product
#
Create a new product
product
= Product(name="Sample Product", description="This is a sample
product.", price=19.99)
product.save()
#
Query all products
all_products
= Product.objects.all()
print(all_products)
10. Running the Application
With
the server running, you can interact with the application through the web interface
and the Django shell. You can create, read, update, and delete records using
the ORM.
11. Conclusion
This
documentation provided a step-by-step guide on how to integrate Django with
MySQL. You learned how to set up a Django project, configure MySQL, create a
model, and manage your data through the Django admin interface.
12. Summary
- Overview:
Django is a web framework; MySQL is a database. Integration allows for
robust applications.
- Installation:
Install MySQL, Django, and the MySQL Python driver.
- Configuration:
Set up the database in Django settings.
- Model
Creation: Define models
in Django to represent database tables.
- Admin
Interface: Use Django's
admin to manage data easily.
- Querying: Interact with the database using Django's ORM.
Django REST
API with MySQL: Complete Documentation
Introduction
Django is a
high-level Python web framework that encourages rapid development and clean,
pragmatic design. When combined with Django REST framework (DRF), it becomes an
excellent choice for building RESTful APIs. This documentation will guide you
through setting up a Django REST API connected to a MySQL database, complete
with examples and best practices.
Prerequisites
- Python: Ensure you have
Python installed (preferably 3.6 or later).
- MySQL: Install MySQL
Server and have a database ready for use.
- Pip: Make sure you
have
pip
for package management.
Installation
Step 1: Set up
a virtual environment
Bash
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate
Step 2:
Install Django and Django REST framework
Bash
pip install django djangorestframework mysqlclient
Step 3: Create
a Django project
Bash
django-admin startproject myproject
cd myproject
Step 4: Create
a Django app
Bash
python manage.py startapp myapp
Step 5: Update
settings
Edit myproject/settings.py
to configure the MySQL
database and add the new app and REST framework.
Python
# myproject/settings.py
INSTALLED_APPS = [
...
'rest_framework',
'myapp',
]
DATABASES = {
'default': {
'ENGINE':
'django.db.backends.mysql',
'NAME':
'your_database_name',
'USER':
'your_username',
'PASSWORD':
'your_password',
'HOST':
'localhost',
'PORT':
'3306',
}
}
Step 6: Create
the database
Make sure you
create the database in MySQL before running migrations.
Sql
CREATE DATABASE your_database_name;
Creating a
Model
Let's create a
simple Product
model.
Python
# myapp/models.py
from django.db
import models
class
Product(models.Model):
name = models.CharField(max_length=
100)
description = models.TextField()
price = models.DecimalField(max_digits=
10, decimal_places=
2)
def
__str__(
self):
return self.name
Step 7: Run
migrations
Bash
python manage.py makemigrations
python manage.py migrate
Creating a
Serializer
Create a
serializer for the Product
model.
Python
# myapp/serializers.py
from rest_framework
import serializers
from .models
import Product
class
ProductSerializer(serializers.ModelSerializer):
class
Meta:
model = Product
fields =
'__all__'
Creating Views
Use Django REST
framework to create views for your API.
Python
# myapp/views.py
from rest_framework
import viewsets
from .models
import Product
from .serializers
import ProductSerializer
class
ProductViewSet(viewsets.ModelViewSet):
queryset = Product.objects.
all()
serializer_class = ProductSerializer
Configuring
URLs
Now, connect your
views to URLs.
Python
# myapp/urls.py
from django.urls
import path, include
from rest_framework.routers
import DefaultRouter
from .views
import ProductViewSet
router = DefaultRouter()
router.register(
r'products', ProductViewSet)
urlpatterns = [
path(
'', include(router.urls)),
]
Include the app
URLs in the main project's URL configuration.
Python
# myproject/urls.py
from django.contrib
import admin
from django.urls
import path, include
urlpatterns = [
path(
'admin/', admin.site.urls),
path(
'api/', include(
'myapp.urls')),
]
Testing the
API
Step 8: Run
the server
Bash
python manage.py runserver
Step 9: Test
your API
You can use
tools like Postman or cURL to interact with your API. Here are the endpoints:
- GET
/api/products/
- List all products. - POST
/api/products/
- Create a new product. - GET
/api/products/{id}/
- Retrieve a specific product. - PUT
/api/products/{id}/
- Update a specific product. - DELETE
/api/products/{id}/
- Delete a specific product.
Example
Request/Response
Creating
a Product:
Request:
http
POST /api/products/
Content-Type: application/json
{
"name": "Sample Product",
"description": "This is a sample product.",
"price": 19.99
}
Response:
Json
{
"id":
1,
"name":
"Sample Product",
"description":
"This is a sample product.",
"price":
"19.99"
}
Summary
- Setting up Django with
MySQL:
We configured Django to use MySQL and created a simple database.
- Creating a REST API: We built a
Product
model, created serializers, and defined views using Django REST framework. - Testing the API: We used HTTP methods to interact with our API endpoints.
Django CRUD
Operations with MySQL: Complete Documentation
Introduction
Django is a
powerful web framework that simplifies web application development. This
documentation provides a comprehensive guide to performing Create, Read,
Update, and Delete (CRUD) operations using Django with a MySQL database. By the
end, you'll have a fully functional example to reference.
Prerequisites
- Python: Make sure Python
3.6 or later is installed.
- MySQL: Install MySQL
Server and create a database.
- Pip: Ensure you have
pip
for package management.
Installation
Step 1: Set up
a virtual environment
Bash
# Create a virtual environment
python -m venv myenv
# Activate the virtual environment
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate
Step 2:
Install Django and MySQL client
Bash
pip install django mysqlclient
Step 3: Create
a Django project
Bash
django-admin startproject myproject
cd myproject
Step 4: Create
a Django app
Bash
python manage.py startapp myapp
Step 5:
Configure the database
Edit myproject/settings.py
to set up MySQL:
Python
# myproject/settings.py
INSTALLED_APPS = [
...
'myapp',
]
DATABASES = {
'default': {
'ENGINE':
'django.db.backends.mysql',
'NAME':
'your_database_name',
'USER':
'your_username',
'PASSWORD':
'your_password',
'HOST':
'localhost',
'PORT':
'3306',
}
}
Step 6: Create
the database
Make sure you
create the database in MySQL before running migrations:
Sql
CREATE DATABASE your_database_name;
Creating a
Model
Let's create a
simple Product
model.
Python
# myapp/models.py
from django.db
import models
class
Product(models.Model):
name = models.CharField(max_length=
100)
description = models.TextField()
price = models.DecimalField(max_digits=
10, decimal_places=
2)
def
__str__(
self):
return self.name
Step 7: Run
migrations
Bash
python manage.py makemigrations
python manage.py migrate
Creating CRUD
Views
Step 8: Create
Views
Edit myapp/views.py
to implement CRUD
operations.
Python
# myapp/views.py
from django.shortcuts
import render, redirect, get_object_or_404
from .models
import Product
from .forms
import ProductForm
def
product_list(
request):
products = Product.objects.
all()
return render(request,
'myapp/product_list.html', {
'products': products})
def
product_create(
request):
if request.method ==
'POST':
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return redirect(
'product_list')
else:
form = ProductForm()
return render(request,
'myapp/product_form.html', {
'form': form})
def
product_update(
request, pk):
product = get_object_or_404(Product, pk=pk)
if request.method ==
'POST':
form = ProductForm(request.POST, instance=product)
if form.is_valid():
form.save()
return redirect(
'product_list')
else:
form = ProductForm(instance=product)
return render(request,
'myapp/product_form.html', {
'form': form})
def
product_delete(
request, pk):
product = get_object_or_404(Product, pk=pk)
if request.method ==
'POST':
product.delete()
return redirect(
'product_list')
return render(request,
'myapp/product_confirm_delete.html', {
'product': product})
Step 9: Create
Forms
Create a form
for the Product
model.
Python
# myapp/forms.py
from django
import forms
from .models
import Product
class
ProductForm(forms.ModelForm):
class
Meta:
model = Product
fields = [
'name',
'description',
'price']
Step 10: Configure
URLs
Set up URLs for
your CRUD operations.
Python
# myapp/urls.py
from django.urls
import path
from .views
import product_list, product_create, product_update, product_delete
urlpatterns = [
path(
'', product_list, name=
'product_list'),
path(
'create/', product_create, name=
'product_create'),
path(
'update/<int:pk>/', product_update, name=
'product_update'),
path(
'delete/<int:pk>/', product_delete, name=
'product_delete'),
]
Include the app
URLs in the main project's URL configuration.
Python
# myproject/urls.py
from django.contrib
import admin
from django.urls
import path, include
urlpatterns = [
path(
'admin/', admin.site.urls),
path(
'products/', include(
'myapp.urls')),
]
Step 11: Create Templates
Create the following HTML templates in a
directory called templates/myapp
.
- product_list.html
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product List
</title>
</head>
<body>
<h1>Product List
</h1>
<a href="{% url 'product_create' %}">Add New Product
</a>
<ul>
{% for product in products %}
<li>
{{ product.name }} - {{ product.price }}
<a href="{% url 'product_update' product.pk %}">Edit
</a>
<a href="{% url 'product_delete' product.pk %}">Delete
</a>
</li>
{% endfor %}
</ul>
</body>
</html>
- product_form.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Product Form
</title>
</head>
<body>
<h1>{% if form.instance.pk %}Edit{% else %}Add{% endif %} Product
</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save
</button>
</form>
</body>
</html>
- product_confirm_delete.html
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Delete Product
</title>
</head>
<body>
<h1>Are you sure you want to delete "{{ product.name }}"?
</h1>
<form method="post">
{% csrf_token %}
<button type="submit">Confirm
</button>
</form>
<a href="{% url 'product_list' %}">Cancel
</a>
</body>
</html>
Testing the
Application
Step 12: Run
the server
Bash
python manage.py runserver
Step 13:
Access the application
Navigate to http://127.0.0.1:8000/products/
in your browser to
access the product management application.
Summary
- Setting
Up Django with MySQL: Configured Django to
work with a MySQL database and created a basic project structure.
- Creating
a Model:
Defined a simple
Product
model. - Implementing
CRUD Operations: Created views for listing, creating,
updating, and deleting products.
- Forms
and Templates: Designed forms and templates to
handle user input and display data.
- Running
the Application: Successfully launched the
application and performed CRUD operations.
No comments:
Post a Comment