Skip to content

A example of how to make a Django Project and make a CRUD using Mysql Database, Virtualenv and Decouple.

Notifications You must be signed in to change notification settings

GDS2005/django-crud

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CRUD Django Example

An example of how to use the Django Framework to create a CRUD application of Books in MySQL.

Start a new Django Project

  1. Install Django
pip install django
  1. Create a new project. Replace "myproject" with your project name. It's common to use uppercase letters at the start of each word, such as "BookStore"
python -m django startproject myproject
  1. Enter the project folder
cd myproject
  1. Install Virtualenv. Virtualenv allows you to create isolated Python environments. This is especially useful for managing dependencies and avoiding conflicts between packages used in different projects.
pip install virtualenv
  1. Create a Virtual Environment. Replace "myenv" with the name of your virtual environment. I usually use the name "venv"
python3 -m venv myenv
  1. Activate the Virtual Environment. This depends on your operating system.
  • Windows:
venv\Scripts\activate
  • Linux:
source venv/bin/activate
  1. Now you can install dependencies, and they will be isolated. To use it, just install a dependency.
pip install django

Then you must run:

pip freeze > requirements.txt

With this, you can store all the project dependencies in this file, which is useful for Docker and server deployments.

  1. Use deactivate to exit the Virtual Environment.
deactivate
  1. Run the project by executing:
python manage.py runserver

django-basic Image

Generate CRUD (Create, Read, Update and Delete) of elements

  1. First, we need to create an app. A Django app is a modular component representing a discrete part of a larger project. The app name should be short, all-lowercase, and not include numbers, dashes, periods, spaces, or special characters. It should generally be the plural form of an app's main model.
python3 manage.py startapp appname
  1. Add the new app to the config/settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'appname', <--
]
  1. Define the model. In appname/models.py, define the model. For example:
from django.db import models

class Book(models.Model):
    title = models.CharField(max_length=100)
    author = models.CharField(max_length=100)
    description = models.TextField()
    price = models.DecimalField(max_digits=10, decimal_places=2)

    class Meta:
        db_table = 'books' 

        def __str__(self):
            return self.id
  1. Create forms to manage the CRUD. In appname, create a file named forms.py for the Book model
from django import forms
from .models import Book

class BookForm(forms.ModelForm):
    class Meta:
        model = Book
        fields = ['title', 'author', 'description', 'price']
  1. In appname/views.py, create functions for the CRUD operations, for example:
from django.shortcuts import render, get_object_or_404, redirect
from .models import Book
from .forms import BookForm

def book_list(request):
    books = Product.objects.all()
    return render(request, 'books/book_list.html', {'books': books})
  1. Define the URL patterns in a urls.py file within your app:
from django.urls import path
from .views import book_list

urlpatterns = [
    path('', book_list, name='book_list'),
]   
  1. Include the app's URLs in the main project. In myproject/urls.py, add:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('books.urls')),
]
  1. Create the template to add HTML content. Create a folder named templates in the app's directory.

Configure Database

I highly recommend using Decouple to use environment variables.

pip install python-decouple

Then, create a ".env" file and define your variables:

DB_HOST=localhost
DB_PORT=3306
DB_NAME=my_database
DB_USER=my_user
DB_PASSWORD=my_password

Import the Decouple package wherever you need it.

from decouple import config
  1. Install te database.
  • Mysql
pip install mysqlclient
  • MongoDB
pip install djongo
  • Postgress
pip install psycopg2
  1. Depending on our database, we need to modify the DATABASE configuration in myproject/config.py:
  • Mysql:
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.mysql",
        "NAME": config('DB_NAME'),
        "USER": config('DB_USER'),
        "PASSWORD": config('DB_PASSWORD'),
        "HOST": config('DB_HOST'),
        "PORT": config('DB_PORT'),
    }
}
  • Sqlite:
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}
  • MongoDB:
DATABASES = {
    'default': {
        'ENGINE' : 'djongo',
        'NAME' : config('DB_NAME'),
        'HOST': config('DB_HOST'),
        'PORT': config('DB_PORT'),
        'USERNAME': config('DB_USER'),
        'PASSWORD': config('DB_PASSWORD'),
        'MONGO_URI': "mongodb://admin:mypwd@127.0.0.127017/bookstorage"
    }
}
  • Postgres:
DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": config('DB_NAME'),
        "USER": config('DB_USER'),
        "PASSWORD": config('DB_PASSWORD'),
        "HOST": config('DB_HOST'),
        "PORT": config('DB_PORT'),
    }
}
  1. Make a migration to apply changes to the database. MAKE SURE THE DATABASE IS CREATED.
python3 manage.py makemigrations
python3 manage.py migrate

How to clone and practice with this repository

  1. Clone this repository.
git clone https://github.com/yourusername/your-django-project.git
  1. Install dependencies.
pip install -r requirements.txt
  1. Create the .env file and define the following variables:
DB_HOST=localhost
DB_PORT=3306
DB_NAME=my_database
DB_USER=my_user
DB_PASSWORD=my_password
  1. Create the database.

  2. Run migrations to apply changes to the database.

python3 manage.py makemigrations
python3 manage.py migrate
  1. Run the project:
python manage.py runserver

Contributing

Contributions are welcome!

About

A example of how to make a Django Project and make a CRUD using Mysql Database, Virtualenv and Decouple.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published