DJANGLE-SETUPS

Objectives: STARTUP

Complete Django Notes

Complete Django Notes

Beginner to Advanced — Full Guide

1. Introduction to Django

Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the MVT architecture (Model-View-Template).

  • Model — Handles the database (data structure).
  • View — Contains the logic and connects model to template.
  • Template — Handles HTML and presentation.

2. Setting up Django

  1. Install Python (recommended 3.12+).
  2. Create a Virtual Environment:
    python -m venv venv
    # Activate on Windows:
    venv\Scripts\activate
    # Activate on Mac/Linux:
    source venv/bin/activate
    
  3. Install Django:
    pip install django
  4. Check version:
    python -m django --version

3. Creating a Project

django-admin startproject mysite
cd mysite
python manage.py runserver

Visit http://127.0.0.1:8000 to see the default page.

4. Creating an App

python manage.py startapp blog

Register the app in mysite/settings.py under INSTALLED_APPS.

5. Models

Define your database structure in models.py:

from django.db import models

class Post(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return self.title

6. Migrations

Apply database changes:

python manage.py makemigrations
python manage.py migrate

7. Django Admin

Create a superuser to access the admin panel:

python manage.py createsuperuser

Register models in admin.py:

from django.contrib import admin
from .models import Post

admin.site.register(Post)

Run server and go to /admin.

8. Views and URLs

Create a view in views.py:

from django.http import HttpResponse

def home(request):
    return HttpResponse("Hello, Django!")

Map it in urls.py:

from django.contrib import admin
from django.urls import path
from blog import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.home, name='home'),
]

9. Templates

Create a folder templates and an HTML file home.html:

<h1>Welcome to Django</h1>
<p>This is a template example</p>

Render it in views.py:

from django.shortcuts import render

def home(request):
    return render(request, 'home.html')

10. Static Files

For CSS/JS, create a static folder inside your app and load it in templates using:

{% load static %}
<link rel="stylesheet" href="{% static 'style.css' %}">

11. Deployment

  • Use a production server like Gunicorn or uWSGI.
  • Configure allowed hosts in settings.py.
  • Use a database like PostgreSQL for production.

12. Best Practices

  • Always use virtual environments.
  • Keep settings secret (use environment variables).
  • Write reusable apps.
  • Follow Django security recommendations.
Note: Always deactivate the virtual environment with deactivate when done.

© 2025 Django Full Notes | Created for Educational Purposes

2. Setting up Django

  1. Install Python (recommended 3.12+).
  2. Create a Virtual Environment:
    # Linux / Mac
    python3 -m venv venv
    source venv/bin/activate
    
    # Windows (PowerShell)
    py -3 -m venv venv
    .\venv\Scripts\Activate.ps1
    
    # Windows (Command Prompt)
    py -3 -m venv venv
    venv\Scripts\activate.bat
    
  3. Install Django:
    pip install django
  4. Check version:
    # Linux / Mac
    python3 -m django --version
    
    # Windows
    py -m django --version
    
Django “no such table: auth_user” — Fix Guide

Django “no such table: auth_user” — Definitive Fix Notes

Environment seen in logs: Windows, PowerShell, virtualenv, SQLite, project under OneDrive path.

Symptom

django.db.utils.OperationalError: no such table: auth_user while logging into /admin/ or running createsuperuser.

Also observed

Could not find platform independent libraries <prefix> (usually harmless message when Python can’t locate a “prefix” during startup; see section below if it blocks execution).

Root Cause

  • Core Django apps (auth, admin, contenttypes, sessions) have unapplied migrations, so tables were never created.
  • On Windows with OneDrive, the SQLite file can be missing/locked or the project path changes, so Django looks at a fresh empty DB.
  • Environment variables or wrong interpreter may print the “prefix” warning.

Quick Fix Checklist (run in project root next to manage.py)

1) Activate venv

.\venv\Scripts\activate

2) Verify interpreter & Django

where python


python -V
python -m django --version

3) Show migration state

python manage.py showmigrations

4) Apply migrations

python manage.py makemigrations
python manage.py migrate

5) Create superuser

python manage.py createsuperuser

6) Run server

python manage.py runserver

If You’re Using SQLite (default)

  1. Confirm your DB file exists at the path configured in settings.py:
# settings.py (default)


DATABASES = {
"default": {
"ENGINE": "django.db.backends.sqlite3",
"NAME": BASE_DIR / "db.sqlite3",
}
}
  1. If the DB is missing or corrupted and you have no data to keep, delete it and migrate again:
del .\db.sqlite3
python manage.py migrate
python manage.py createsuperuser
  1. Avoid keeping db.sqlite3 inside OneDrive-synced folders to prevent file locking. Move your project out of OneDrive... or exclude the DB file from sync.

If You’re Using PostgreSQL or MySQL

Ensure the database exists and credentials are correct.

# PostgreSQL example


DATABASES = {
"default": {
"ENGINE": "django.db.backends.postgresql",
"NAME": "mydb",
"USER": "myuser",
"PASSWORD": "mypassword",
"HOST": "localhost",
"PORT": "5432",
}
}
# MySQL example
DATABASES = {
"default": {
"ENGINE": "django.db.backends.mysql",
"NAME": "mydb",
"USER": "myuser",
"PASSWORD": "mypassword",
"HOST": "localhost",
"PORT": "3306",
"OPTIONS": {"charset": "utf8mb4"},
}
}

Then run:

python manage.py migrate
python manage.py createsuperuser

Troubleshooting Common Pitfalls

1) Project Inside OneDrive

  • Move the whole project to a non-synced directory (e.g. C:\Dev\DJANGLE\mysite).
  • Stop the dev server, close DB browser tools, then re-run migrations.

2) Wrong Virtual Environment / Python

.\venv\Scripts\activate


where python
where pip
pip list | findstr Django

If multiple Pythons show up, ensure the first one is inside your venv path.

3) “Could not find platform independent libraries <prefix>”

  • If commands continue to run, this message is harmless.
  • If it blocks execution, remove custom Python environment variables:
# PowerShell (remove user-level overrides)

Close and reopen terminal, reactivate venv
  • Ensure you launch the venv’s Python (.\venv\Scripts\python.exe).

4) App Migrations Present but Not Applied

python manage.py showmigrations auth


python manage.py migrate auth

If initial migrations are detected but not applied due to existing tables created manually, use:

python manage.py migrate --fake-initial

Only use --fake/--fake-initial when you know the DB schema matches the migration state.

5) Reset a Single App’s Migrations (when schema drifted)

  1. Delete migration files in your_app/migrations/ except __init__.py.
  2. Regenerate and apply:
python manage.py makemigrations your_app


python manage.py migrate

6) Admin Login Shows HTTP 500

  • Ensure INSTALLED_APPS includes core apps:
# settings.py


INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
# your apps...
]
  • Confirm URL routing includes admin:
# urls.py
from django.contrib import admin
from django.urls import path

urlpatterns = [
path("admin/", admin.site.urls),
]
  • Re-run:
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Diagnostic Commands (copy & paste)

# From project root


.\venv\Scripts\activate
python manage.py check
python manage.py showmigrations
python manage.py shell -c "from django.conf import settings; print(settings.DATABASES['default'])"
python -c "import sqlite3,os; print('db exists:', os.path.exists('db.sqlite3'))"
python manage.py dbshell # SQLite: opens the SQLite shell (if configured)

Clean Start (Safe if You Have No Data to Keep)

.\venv\Scripts\activate


taskkill /IM python.exe /F # close any dev server using the DB
del .\db.sqlite3
for /d %i in (".**\migrations") do @echo %i

Manually delete ONLY your own app migrations (keep init.py). Do NOT delete django.contrib.* migrations.

python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
python manage.py runserver

Notes for Production Databases

  • Never delete a production database to “fix” migrations; instead, write proper forward/backward migrations.
  • Use python manage.py makemigrations locally, commit migration files, then python manage.py migrate in each environment.
  • For schema drift, create data migrations or use RunPython operations in custom migration files.
Bottom line: Apply migrations first. The error vanishes once auth_user is created by python manage.py migrate. Keep your project out of OneDrive for the DB file, ensure the right venv Python runs, and only “fake” migrations when you fully understand the schema state.

Reference Book: N/A

Author name: SIR H.A.Mwala Work email: biasharaboraofficials@gmail.com
#MWALA_LEARN Powered by MwalaJS #https://mwalajs.biasharabora.com
#https://educenter.biasharabora.com

:: 1::