Getting Started
# Install Django
pip install django
# Start a new project
django-admin startproject myproject
# Run the development server
cd myproject
python manage.py runserver
Creating an App
# Create an app within the project
python manage.py startapp myapp
Models
# myapp/models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Migrations
# Generate migrations for the app
python manage.py makemigrations
# Apply migrations to the database
python manage.py migrate
Views
# myapp/views.py
from django.shortcuts import render
from .models import Post
def index(request):
posts = Post.objects.all()
return render(request, 'index.html', {'posts': posts})
URLs
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
Templates
<!-- templates/index.html -->
<!DOCTYPE html>
<html>
<head>
<title>My Blog</title>
</head>
<body>
<h1>Posts</h1>
<ul>
{% for post in posts %}
<li>{{ post.title }} - {{ post.created_at }}</li>
{% endfor %}
</ul>
</body>
</html>
Django Authentication Setup
Learn how to set up user authentication in Django, including login, logout, and registration functionality.
Authentication Settings
# settings.py
INSTALLED_APPS = [
'django.contrib.auth',
'django.contrib.contenttypes',
]
AUTHENTICATION_BACKENDS = [
'django.contrib.auth.backends.ModelBackend',
]
Login and Logout URLs
# urls.py
from django.contrib.auth import views as auth_views
urlpatterns = [
path('login/', auth_views.LoginView.as_view(), name='login'),
path('logout/', auth_views.LogoutView.as_view(), name='logout'),
]
Register a New User
# views.py
from django.contrib.auth.forms import UserCreationForm
from django.shortcuts import render, redirect
def register(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = UserCreationForm()
return render(request, 'register.html', {'form': form})
# templates/register.html
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Sign Up</button>
</form>
Django REST API Basics
Set up a basic REST API using Django REST Framework (DRF).
Install Rest Framework
pip install djangorestframework
Create and Serialize Models
# models.py
class Book(models.Model):
title = models.CharField(max_length=255)
author = models.CharField(max_length=255)
# serializers.py
from rest_framework import serializers
from .models import Book
class BookSerializer(serializers.ModelSerializer):
class Meta:
model = Book
fields = '__all__'
API Views
# api_views.py
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Book
from .serializers import BookSerializer
@api_view(['GET', 'POST'])
def book_list(request):
if request.method == 'GET':
books = Book.objects.all()
serializer = BookSerializer(books, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = BookSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=201)