Showing posts with label software development. Show all posts
Showing posts with label software development. Show all posts

Thursday, October 3, 2024

makemigrations vs migrate in Django: Key Differences

Django makemigrations vs migrate – Complete Beginner to Advanced Guide

๐Ÿ Django makemigrations vs migrate – Complete Guide

Django provides two core commands for database management:

  • makemigrations – prepares changes
  • migrate – applies changes

They look similar, but they perform completely different roles in the database lifecycle.


๐Ÿ“š Table of Contents


๐Ÿง  Overview

Django separates planning changes and applying changes to the database.

This avoids direct risky changes to the database and ensures version control for schema evolution.


⚙️ What is makemigrations?

This command detects changes in models.py and creates migration files.

Command

python manage.py makemigrations

What it does internally:

  • Scans model changes
  • Compares with last migration
  • Generates Python migration scripts

Example Output

View CLI Output
Migrations for 'app':
  app/migrations/0002_add_age_field.py
    - Add field age to Student

Important Idea

It does NOT change the database. It only prepares instructions.


๐Ÿš€ What is migrate?

This command applies migration files to the database.

Command

python manage.py migrate

What it does internally:

  • Reads migration files
  • Converts them into SQL
  • Executes SQL on database

Example Output

View CLI Output
Applying app.0002_add_age_field... OK

๐Ÿ” Django Migration Workflow

Step-by-step process:

  1. Create or modify model
  2. Run makemigrations
  3. Generate migration file
  4. Run migrate
  5. Database updated

๐Ÿ“ Database Mapping (Simple Mathematical Model)

Think of Django migrations as a transformation function:

\[ Database_{new} = f(Database_{old}, Migration) \]

Explanation:

  • Database_old = current schema
  • Migration = instructions (like rules)
  • f() = transformation engine (Django ORM)
๐Ÿ‘‰ In simple words: Migration is a set of rules that transforms your old database into a new structure.

Another way to think:

\[ Schema_{t+1} = Schema_t + \Delta Changes \]

  • \( \Delta Changes \) = new fields, tables, deletions

๐Ÿ–ฅ️ CLI Example Workflow

Step 1: Create model

class Student(models.Model): name = models.CharField(max_length=100)

Step 2: Run makemigrations

python manage.py makemigrations

Step 3: Migration file created

Generated File
0001_initial.py

Step 4: Apply migration

python manage.py migrate

Step 5: Database updated


⚖️ makemigrations vs migrate

Feature makemigrations migrate
Purpose Create migration files Apply migrations to DB
Affects DB? No Yes
Output Python migration scripts SQL execution
Usage stage Development step Deployment/runtime step

๐Ÿ’ก Best Practices

  • Always run makemigrations after model changes
  • Commit migration files in Git
  • Run migrate before deploying
  • Never edit migration files manually unless necessary

๐ŸŽฏ Final Summary

makemigrations prepares changes.

migrate applies changes.

Together, they ensure safe and structured database evolution in Django applications.

Wednesday, September 25, 2024

A Step-by-Step Guide to Setting Up a Django Project

Django Project Tutorial: Complete Beginner to Advanced Guide | Create Your First Django Application

Complete Django Tutorial: Build Your First Django Project Step by Step

Django is one of the most powerful and widely used Python web frameworks in the world. It enables developers to create secure, scalable, maintainable, and high-performance web applications with significantly less code compared to many alternatives.

Whether you're building a personal blog, an eCommerce platform, a SaaS application, an enterprise dashboard, a social networking platform, or a machine learning web interface, Django provides the tools necessary to accelerate development while maintaining code quality.



Introduction to Django

Django is a high-level Python web framework that follows the philosophy:

The web framework for perfectionists with deadlines.

It was originally developed by developers working in a newsroom environment who needed to create robust web applications rapidly. Since then, Django has evolved into one of the most respected frameworks in the software development ecosystem.

Large organizations including Instagram, Pinterest, Mozilla, and many enterprise platforms have utilized Django in various capacities because of its productivity-focused design.

๐Ÿ’ก Key Takeaway

  • Django is written in Python.
  • Follows DRY (Don't Repeat Yourself).
  • Includes built-in security features.
  • Comes with ORM, Admin Panel, Authentication.
  • Supports rapid development.

Why Learn Django?

Many web frameworks require extensive configuration before development can begin. Django takes a different approach by providing batteries-included functionality.

Major Benefits

  • Fast development cycle
  • Built-in ORM
  • Authentication system
  • Admin dashboard
  • Session management
  • CSRF protection
  • SQL injection protection
  • Scalable architecture
  • Strong community support
Read More: Why Companies Prefer Django

Organizations choose Django because it reduces development time significantly. Instead of writing repetitive infrastructure code, developers focus on business logic.

This translates into faster releases, lower maintenance costs, and improved reliability.


Django Architecture Explained

Django follows the MVT architecture:

  • Model
  • View
  • Template

Model

Models define database structure.

View

Views process requests and generate responses.

Template

Templates handle user interface rendering.

MVT Flow

  1. User sends request.
  2. URL dispatcher receives request.
  3. View processes request.
  4. Model accesses database.
  5. Template renders output.
  6. Response returns to browser.

๐Ÿ“ Mathematics Behind Web Requests

Although web development is not heavily mathematical, understanding performance calculations helps optimize applications.

Request Throughput Formula

Theoretical requests per second:

Requests Per Second = Total Requests / Total Time

Example:

1000 Requests / 20 Seconds = 50 RPS

Meaning your application can serve approximately 50 requests every second.

Response Time Formula

Average Response Time = Total Processing Time / Number of Requests

Example:

5000 ms / 100 requests = 50 ms

Lower response times generally improve user experience.

๐Ÿ’ก Performance Insight

  • Lower latency improves UX.
  • Higher throughput improves scalability.
  • Caching reduces processing time.
  • Database indexing improves query speed.

Step 1: Installing Django

Before creating a Django project, install Django using pip.

Command

pip install django

CLI Output Sample

Collecting django
Downloading Django-5.x.x-py3-none-any.whl
Installing collected packages: django
Successfully installed django

Verify Installation

django-admin --version

Expected Output

5.x.x

Step 2: Creating a Django Project

A Django project acts as the container for your entire web application.

Command

django-admin startproject firstProject

CLI Output Sample

Project created successfully.

Generated Structure

firstProject/
│
├── manage.py
│
└── firstProject/
    ├── __init__.py
    ├── settings.py
    ├── urls.py
    ├── asgi.py
    └── wsgi.py

Understanding Each File

File Purpose
manage.py Project management utility
settings.py Configuration settings
urls.py URL routing
wsgi.py Deployment gateway
asgi.py Async server gateway

Step 3: Creating an Application

A Django project can contain multiple applications.

Think of a project as a company and applications as departments.

Command

python manage.py startapp firstApp

CLI Output Sample

Application created successfully.

Generated Structure

firstApp/

admin.py
apps.py
models.py
views.py
tests.py
migrations/

Purpose of Files

  • views.py → business logic
  • models.py → database structure
  • admin.py → admin interface
  • tests.py → testing
  • apps.py → app configuration

Step 4: Add Application to INSTALLED_APPS

Django must know your application exists.

Open settings.py

Code Example

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'firstApp',
]

After saving, Django will register your application.


Step 5: Creating Your First View

A view receives requests and returns responses.

Code Example

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello World")

Explanation

  • request contains user information.
  • HttpResponse sends data back.
  • home() is executed whenever mapped URL is visited.

Step 6: Configuring URLs

URLs tell Django which view should run.

Create app-level urls.py

from django.urls import path
from .views import home

urlpatterns = [
    path('', home, name='home'),
]

Main Project URLs

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('', include('firstApp.urls')),
    path('admin/', admin.site.urls),
]

Step 7: Running Development Server

python manage.py runserver

CLI Output Sample

Watching for file changes with StatReloader

System check identified no issues

Starting development server at

http://127.0.0.1:8000/

Quit the server with CTRL+C

Visit:

http://127.0.0.1:8000/

You should see:

Hello World

Understanding Request Response Cycle

  1. User enters URL.
  2. Browser sends HTTP request.
  3. Django URL router checks patterns.
  4. Matching view executes.
  5. View processes business logic.
  6. Database query executes if required.
  7. Response generated.
  8. Browser displays result.
Deep Dive into Request Lifecycle

Every request starts with the browser establishing a connection to the web server. The web server forwards the request to Django. Django loads middleware, performs authentication checks, resolves URLs, executes views, and returns a response object.

Understanding this lifecycle is essential for debugging and optimization.


๐ŸŽฏ Django Best Practices

  • Use virtual environments.
  • Separate settings for development and production.
  • Write reusable applications.
  • Use environment variables.
  • Follow DRY principle.
  • Write tests regularly.
  • Use migrations correctly.
  • Optimize database queries.
  • Use caching when necessary.
  • Keep dependencies updated.

๐Ÿ’ก Important Learning Summary

  • Django follows MVT architecture.
  • A project can contain multiple apps.
  • Views handle business logic.
  • URLs connect requests to views.
  • Templates render HTML.
  • Models manage database operations.
  • The development server helps local testing.
  • Django provides strong security out of the box.

Frequently Asked Questions

1. What is Django?

Django is a Python web framework designed for rapid application development.

2. Is Django frontend or backend?

Django is primarily a backend framework.

3. Does Django use SQL?

Yes. Django uses an ORM that translates Python code into SQL queries.

4. Can Django handle large traffic?

Yes. Many large-scale platforms use Django in production.

5. Why is Django popular?

Because it provides security, scalability, maintainability, and rapid development.


Final Thoughts

Django remains one of the best frameworks for learning professional web development. By understanding project creation, application structure, views, URL routing, settings configuration, and request-response handling, you build a strong foundation for creating complex web applications.

The next logical topics after mastering this tutorial are:

  • Django Models
  • Django ORM
  • Django Templates
  • Django Forms
  • Django Authentication
  • Django Middleware
  • Django REST Framework
  • Django Deployment
  • Django Security
  • Django Performance Optimization

Master these concepts and you will be capable of building production-ready web applications using Django.

Monday, September 9, 2024

Why You Shouldn't Delete the .git Folder: Understanding Common Git Commit Issues


Why Deleting the .git Folder Is a Bad Idea

Why Deleting the .git Folder Is a Bad Idea

And what to do instead when Git commits stop working

The .git folder is the heart of a Git repository. It stores all metadata, commit history, branches, and configuration. Deleting it removes Git tracking entirely.

If you find yourself deleting the .git folder frequently, it usually means there’s an underlying workflow or configuration problem that needs fixing—not resetting.

⚠️ Important: Deleting the .git folder permanently removes your version history. This should only be done as a last resort.

Common Reasons Why Commits Fail

1️⃣ Repository Corruption

Git repositories can occasionally become corrupted due to disk issues, abrupt shutdowns, or interrupted operations.

git fsck

This command checks the integrity of the repository and reports problems.

2️⃣ Detached HEAD State

A detached HEAD occurs when you check out a specific commit instead of a branch. Commits made here may appear “lost.”

git checkout <branch-name>
3️⃣ Uncommitted Changes or Merge Conflicts

Unresolved conflicts or staged issues can block commits.

git status

Git will guide you to resolve conflicts before committing.

4️⃣ Incorrect Git Configuration

Missing username or email settings can prevent commits.

git config --list

Set them if missing:

git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

Why Deleting .git Seems to Work

Deleting the .git folder resets everything, making Git forget all history and configuration. This may temporarily remove the symptom, but it also removes valuable data and context.

What to Do Instead

✅ Reinitialize Git (Without Losing History)
git init

This refreshes Git metadata without deleting commit history.

๐Ÿ“ฆ Stash Pending Changes
git stash
git stash apply
๐Ÿ”ง Resolve Merge Conflicts
git add <conflicted-file>
git commit
๐Ÿ” Check Permissions & File Locks

Ensure files are writable and not locked by:

  • IDEs
  • Background processes
  • Operating system permissions
๐Ÿช Check Git Hooks

Broken pre-commit or commit hooks can block commits. Check:

.git/hooks/
๐Ÿ“ฅ Reclone the Repository
git clone <repository-url>

This is safer than deleting .git locally.

๐Ÿ’ก Key Takeaways

  • The .git folder is essential and should not be deleted casually
  • Commit issues usually indicate workflow or config problems
  • Git provides tools to diagnose and fix most issues
  • Recloning is safer than wiping history
  • Deleting .git should be a last resort
Git best practices: fixing commit issues without destroying history

Featured Post

How HMT Watches Lost the Time: A Deep Dive into Disruptive Innovation Blindness in Indian Manufacturing

The Rise and Fall of HMT Watches: A Story of Brand Dominance and Disruptive Innovation Blindness The Rise and Fal...

Popular Posts