We use cookies to understand how the site is used and to display ads. Analytics and advertising only run after you accept. You can change your choice anytime. Privacy policy

Skip to content
devvkit
$devvkit learn --librarie django-guide

Django Guide

[python][web][full-stack]
Python
Install
pip install django
django-admin startproject myproject

Django comes with everything: ORM, admin panel, authentication, forms, and template engine.

The ORM supports model inheritance, complex querysets, migrations, and raw SQL.

Django REST Framework provides serializers, viewsets, and browsable API documentation.

Setup

Create project· Scaffold new project.
django-admin startproject myproject
cd myproject
python manage.py runserver
Create app· New app.
python manage.py startapp blog
# Add 'blog' to INSTALLED_APPS

Models & ORM

Define model· Database model.
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)
    author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
Migrations· Apply schema changes.
python manage.py makemigrations
python manage.py migrate
QuerySet· Query database.
Post.objects.filter(author__username='admin')
Post.objects.get(id=1)
Post.objects.order_by('-created_at')[:5]
Create record· Insert data.
Post.objects.create(title='Hello', content='World', author=User.objects.first())

Views & URLs

Class-based view· Generic list view.
from django.views.generic import ListView
class PostListView(ListView):
    model = Post
    template_name = 'blog/post_list.html'
URL config· Map URLs.
from django.urls import path
from . import views
urlpatterns = [
    path('', views.PostListView.as_view(), name='list'),
    path('<int:pk>/', views.post_detail, name='detail'),
]

Admin

Admin registration· Make model editable in admin.
from django.contrib import admin
from .models import Post
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
    list_display = ('title', 'author', 'created_at')

Django REST Framework

DRF ViewSet· CRUD API endpoint.
from rest_framework import viewsets
class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.all()
    serializer_class = PostSerializer
DRF Router· Auto URL routes.
from rest_framework.routers import DefaultRouter
router = DefaultRouter()
router.register('posts', PostViewSet)
urlpatterns = router.urls

Testing

pytest-django· Test with DB.
import pytest
@pytest.mark.django_db
def test_create_post():
    post = Post.objects.create(title='Test', content='...', author=user)
    assert Post.objects.count() == 1