Django on Localhost

Django is Python's most complete web framework — it includes an ORM, authentication, admin panel, form handling, template engine, and security features out of the box. The development server runs on localhost:8000. The auto-generated admin panel is at /admin.

Dev server:localhost:8000

Quick Start

# Install Django
pip install django

# Create a new project
django-admin startproject myproject
cd myproject

# Create an app
python manage.py startapp blog

# Apply migrations
python manage.py migrate

# Create superuser (for /admin)
python manage.py createsuperuser

# Run development server
python manage.py runserver
# Runs at http://localhost:8000 by default

# Custom port
python manage.py runserver 8080

Project Structure

myproject/
├── manage.py
├── myproject/
│   ├── settings.py      # Database, apps, middleware config
│   ├── urls.py          # Root URL routing
│   └── wsgi.py / asgi.py
└── blog/
    ├── models.py        # Database models (ORM)
    ├── views.py         # Request handlers
    ├── urls.py          # App URL patterns
    ├── admin.py         # Admin panel registration
    └── templates/       # HTML templates

A Complete Django App Example

# blog/models.py
from django.db import models

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

    def __str__(self):
        return self.title

# blog/admin.py — register to see in /admin
from django.contrib import admin
from .models import Post
admin.site.register(Post)

# blog/views.py
from django.shortcuts import render
from .models import Post

def post_list(request):
    posts = Post.objects.all().order_by('-created_at')
    return render(request, 'blog/post_list.html', {'posts': posts})

# blog/urls.py
from django.urls import path
from . import views

urlpatterns = [
    path('', views.post_list, name='post_list'),
]

# myproject/urls.py — add to root URLconf
from django.urls import path, include
urlpatterns = [
    path('admin/', admin.site.urls),
    path('blog/', include('blog.urls')),
]

# Create and apply migrations
python manage.py makemigrations
python manage.py migrate

Database Configuration

Django defaults to SQLite for development. For production, switch in settings.py:

# settings.py

# PostgreSQL
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'mydb',
        'USER': 'myuser',
        'PASSWORD': 'mypassword',
        'HOST': 'localhost',
        'PORT': '5432',
    }
}

# MySQL
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'mydb',
        'USER': 'root',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306',
    }
}

Django REST Framework (API)

# pip install djangorestframework
# settings.py: add 'rest_framework' to INSTALLED_APPS

from rest_framework import serializers, viewsets, routers

class PostSerializer(serializers.ModelSerializer):
    class Meta:
        model = Post
        fields = '__all__'

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer

# urls.py
router = routers.DefaultRouter()
router.register('posts', PostViewSet)
urlpatterns += router.urls
# API browsable at http://localhost:8000/posts/

Common Errors

ALLOWED_HOSTS error: In production (DEBUG=False), Django rejects requests to unrecognized hostnames. Add your domain to ALLOWED_HOSTS = ['yourdomain.com', 'localhost'] in settings.py.

No such table: You added a model but forgot to run python manage.py makemigrations and python manage.py migrate.

CSRF verification failed: POST requests from forms require a {% csrf_token %} tag inside the form in the template. API clients should include the CSRF token in headers or use SessionAuthentication with DRF.

Static files not serving: In production with a web server (nginx, Apache), configure static file serving separately. Run python manage.py collectstatic to gather all static files. In development with DEBUG=True, Django serves static files automatically.