Essential Django commands and patterns for project setup, models, views, URLs, templates, forms, admin, authentication, and Django REST Framework. Bookmark this page for quick reference.
Project Setup
Command
Description
pip install django
Install Django via pip
django-admin startproject myproject
Create a new Django project
django-admin startproject myproject .
Create project in the current directory (no extra nesting)
python manage.py startapp myapp
Create a new app inside the project
python manage.py runserver
Start the development server on port 8000
python manage.py runserver 0.0.0.0:8080
Run dev server on a custom host and port
python manage.py check
Check for project issues without running migrations
python manage.py shell
Open an interactive Python shell with Django loaded
from django import forms
from .models import Article
class ArticleForm(forms.ModelForm):
class Meta:
model = Article
fields = ['title', 'slug', 'body', 'tags', 'published']
# or: exclude = ['author', 'created_at']
widgets = {
'body': forms.Textarea(attrs={
'rows': 10,
'placeholder': 'Write your article...'
}),
'title': forms.TextInput(attrs={
'class': 'form-control'
}),
}
labels = {
'body': 'Article Content',
}
help_texts = {
'slug': 'URL-friendly identifier (letters, numbers, hyphens)',
}
def clean_title(self):
title = self.cleaned_data['title']
if len(title) < 5:
raise forms.ValidationError('Title must be at least 5 characters.')
return title
Regular Form
class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
def clean_email(self):
email = self.cleaned_data['email']
if not email.endswith('@example.com'):
raise forms.ValidationError('Must use a company email.')
return email
Form in Template
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>
<!-- Manual field rendering -->
<form method="post">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
<label for="{{ field.id_for_label }}">{{ field.label }}</label>
{{ field }}
{% if field.errors %}
<span class="error">{{ field.errors.0 }}</span>
{% endif %}
</div>
{% endfor %}
<button type="submit">Save</button>
</form>
# models.py (set up BEFORE first migration)
from django.contrib.auth.models import AbstractUser
class CustomUser(AbstractUser):
bio = models.TextField(blank=True)
avatar = models.ImageField(upload_to='avatars/', blank=True)
# settings.py
AUTH_USER_MODEL = 'myapp.CustomUser'
from rest_framework import serializers
from .models import Article
class ArticleSerializer(serializers.ModelSerializer):
author_name = serializers.ReadOnlyField(source='author.username')
class Meta:
model = Article
fields = ['id', 'title', 'slug', 'body', 'author', 'author_name',
'published', 'created_at']
read_only_fields = ['author', 'created_at']
ViewSets and Routers
from rest_framework import viewsets, permissions
from rest_framework.decorators import action
from rest_framework.response import Response
from .models import Article
from .serializers import ArticleSerializer
class ArticleViewSet(viewsets.ModelViewSet):
queryset = Article.objects.all()
serializer_class = ArticleSerializer
permission_classes = [permissions.IsAuthenticatedOrReadOnly]
lookup_field = 'slug'
def perform_create(self, serializer):
serializer.save(author=self.request.user)
@action(detail=True, methods=['post'])
def publish(self, request, slug=None):
article = self.get_object()
article.published = True
article.save()
return Response({'status': 'published'})
# api_urls.py
from rest_framework.routers import DefaultRouter
from .views import ArticleViewSet
router = DefaultRouter()
router.register(r'articles', ArticleViewSet)
urlpatterns = router.urls
DRF Quick Reference
Class
Description
serializers.ModelSerializer
Auto-generates fields from a model
viewsets.ModelViewSet
Full CRUD (list, create, retrieve, update, destroy)
viewsets.ReadOnlyModelViewSet
Read-only (list and retrieve)
generics.ListCreateAPIView
GET (list) and POST (create)
generics.RetrieveUpdateDestroyAPIView
GET, PUT/PATCH, DELETE for one object
permissions.IsAuthenticated
Allow only authenticated users
permissions.IsAdminUser
Allow only admin/staff users
permissions.AllowAny
Allow all (public)
Common Commands
Command
Description
python manage.py runserver
Start development server
python manage.py makemigrations
Create new migration files
python manage.py migrate
Apply database migrations
python manage.py createsuperuser
Create an admin superuser
python manage.py shell
Interactive Python shell with Django
python manage.py dbshell
Open native database CLI
python manage.py test
Run all tests
python manage.py test myapp.tests.TestArticle
Run a specific test class
python manage.py collectstatic
Collect static files into STATIC_ROOT
python manage.py flush
Delete all data from the database
python manage.py dumpdata myapp > data.json
Export app data as JSON
python manage.py loaddata data.json
Import data from a JSON fixture
python manage.py showmigrations
List all migrations and their status
python manage.py inspectdb
Generate models from an existing database
python manage.py changepassword <username>
Change a user's password
python manage.py clearsessions
Remove expired sessions from the database
Frequently Asked Questions
What is the difference between a Django project and a Django app?
A Django project is the entire web application, created with django-admin startproject. It contains settings, root URL configuration, and WSGI/ASGI entry points. A Django app is a modular component within a project that handles a specific feature (e.g., blog, users, payments). Apps are created with python manage.py startapp and must be added to INSTALLED_APPS in settings.py. A single project can contain many apps, and apps can be reused across multiple projects.
When should I use function-based views vs class-based views in Django?
Function-based views (FBVs) are simpler, more explicit, and easier to understand for beginners or for straightforward logic. Class-based views (CBVs) provide built-in mixins and generic views (ListView, DetailView, CreateView) that reduce boilerplate for common patterns like CRUD operations. Use FBVs when the view logic is simple or highly custom. Use CBVs when you need inheritance, reusable mixins, or when your views follow standard patterns that Django's generic views already handle.
How do Django migrations work and when should I create them?
Django migrations are Python files that describe changes to your database schema. When you modify a model (add a field, change a field type, delete a model), run python manage.py makemigrations to generate a migration file, then python manage.py migrate to apply it to the database. Django tracks which migrations have been applied in a django_migrations table. Create migrations every time you change your models. Never edit migration files manually unless you understand the consequences, and always commit migration files to version control.