Youssef Samir

Get in touch

Django

Learn Django, a high-level Python web framework that promotes rapid development and clean, pragmatic design.

Basic Commands

Start a New Project

django-admin startproject projectname

Start a New App

python manage.py startapp appname

Run the Development Server

python manage.py runserver

Apply Migrations

python manage.py migrate

Create New Migrations

python manage.py makemigrations

Create a Superuser

python manage.py createsuperuser

Open Django Shell

python manage.py shell

Project Structure

myproject/
├── manage.py
├── myproject/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   ├── wsgi.py
│   └── asgi.py
└── appname/
    ├── __init__.py
    ├── admin.py
    ├── apps.py
    ├── models.py
    ├── tests.py
    ├── views.py
    ├── urls.py  # (create this file manually)
    └── migrations/

Settings Configuration

Add an App to INSTALLED_APPS

INSTALLED_APPS = [
    # other apps
    'appname',
]

Database Configuration

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'dbname',
        'USER': 'username',
        'PASSWORD': 'password',
        'HOST': 'localhost',
        'PORT': '',
    }
}

Static Files

STATIC_URL = '/static/'
STATICFILES_DIRS = [BASE_DIR / "static"]

MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / "media"

Models

Define a Model

from django.db import models

class ModelName(models.Model):
    fieldname = models.CharField(max_length=255)
    integer_field = models.IntegerField()
    date_field = models.DateField()

    def __str__(self):
        return self.fieldname

Common Field Types

CharField(max_length=255)
TextField()
IntegerField()
FloatField()
BooleanField(default=False)
DateField()
DateTimeField(auto_now_add=True, auto_now=True)
ForeignKey(ModelName, on_delete=models.CASCADE)
ManyToManyField(ModelName)

Run Migrations

python manage.py makemigrations
python manage.py migrate

Views

Function-Based View

from django.shortcuts import render

def my_view(request):
    context = {"key": "value"}
    return render(request, 'template.html', context)

Class-Based View

from django.views import View

class MyView(View):
    def get(self, request):
        context = {"key": "value"}
        return render(request, 'template.html', context)

Common HTTP Responses

from django.http import HttpResponse, Http404, JsonResponse

def my_view(request):
    return HttpResponse("Hello, World!")

def my_json_view(request):
    return JsonResponse({"key": "value"})

URLs

Include an App's URLs in Project URLs

from django.urls import path, include

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

Define URLs in an App

from django.urls import path
from . import views

urlpatterns = [
    path('', views.my_view, name='home'),
    path('detail/<int:id>/', views.detail_view, name='detail'),
]

Templates

Render a Template in a View

from django.shortcuts import render

def my_view(request):
    return render(request, 'template.html', {"key": "value"})

Use Template Inheritance

<!-- base.html -->
<!DOCTYPE html>
<html>
  <head>
    <title>{% block title %}My Site{% endblock %}</title>
  </head>
  <body>
    {% block content %}{% endblock %}
  </body>
</html>

<!-- child_template.html -->
{% extends "base.html" %} {% block title %}Child Template{% endblock %} {% block
content %}
<h1>Content from Child Template</h1>
{% endblock %}

Use Template Tags

{% if condition %}
<p>Condition is True</p>
{% else %}
<p>Condition is False</p>
{% endif %} {% for item in list %}
<p>{{ item }}</p>
{% endfor %} {{ variable }} {{ variable|filter }}

Forms

Create a Form

from django import forms

class MyForm(forms.Form):
    name = forms.CharField(max_length=255)
    email = forms.EmailField()

Handle a Form in a View

from .forms import MyForm

def my_view(request):
    if request.method == 'POST':
        form = MyForm(request.POST)
        if form.is_valid():
            # process form data
            pass
    else:
        form = MyForm()

    return render(request, 'template.html', {'form': form})

Admin

Register a Model

from django.contrib import admin
from .models import ModelName

@admin.register(ModelName)
class ModelNameAdmin(admin.ModelAdmin):
    list_display = ('field1', 'field2')
    search_fields = ('field1',)

Authentication

User Authentication

from django.contrib.auth import authenticate, login, logout

# Authenticate User
user = authenticate(request, username='username', password='password')

# Log In
if user is not None:
    login(request, user)

# Log Out
logout(request)

Restrict Access to Logged-In Users

from django.contrib.auth.decorators import login_required

@login_required
def my_view(request):
    return render(request, 'template.html')

Deployment

Collect Static Files

python manage.py collectstatic

Gunicorn Example

gunicorn myproject.wsgi:application --bind 0.0.0.0:8000

Nginx Example (Basic Configuration)

server {
    listen 80;
    server_name yourdomain.com;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /path/to/staticfiles;
    }

    location /media/ {
        root /path/to/media;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/path/to/yourproject.sock;
    }
}