Complete Django Notes
JAMALIHASSAN0307
May 19, 2025
Contents
1 Models in Django 2
1.1 Applying Constraints in Django Models . . . . . . . . . . . . . . 2
1.2 Relationships Between Tables and Fields . . . . . . . . . . . . . . 3
1.3 Model Methods and Query Optimization . . . . . . . . . . . . . . 4
1.3.1 Basic Methods . . . . . . . . . . . . . . . . . . . . . . . . 4
1.3.2 QuerySet Methods . . . . . . . . . . . . . . . . . . . . . . 4
1.3.3 Optimization Methods . . . . . . . . . . . . . . . . . . . . 4
1.4 Migration in Django . . . . . . . . . . . . . . . . . . . . . . . . . 4
2 User Model for Validation 5
2.1 Creating User Profile with Extra Fields . . . . . . . . . . . . . . 5
2.1.1 Option 1: One-to-One Profile . . . . . . . . . . . . . . . . 5
2.1.2 Option 2: Proxy Model . . . . . . . . . . . . . . . . . . . 6
2.2 AbstractUser Model . . . . . . . . . . . . . . . . . . . . . . . . . 6
2.3 User Model and One-to-One Relationship . . . . . . . . . . . . . 6
3 Forms and Validation 6
3.1 ModelForm Concept . . . . . . . . . . . . . . . . . . . . . . . . . 6
3.2 Meta Class Configuration . . . . . . . . . . . . . . . . . . . . . . 7
3.3 Form Validation Techniques . . . . . . . . . . . . . . . . . . . . . 7
3.3.1 Field Validation . . . . . . . . . . . . . . . . . . . . . . . 7
3.3.2 Form-wide Validation . . . . . . . . . . . . . . . . . . . . 7
3.3.3 Validators . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4 Serialization 8
4.1 Creating Serializers . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.2 Nested Serializers . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
4.3 Serializer Validation . . . . . . . . . . . . . . . . . . . . . . . . . 9
4.3.1 Field-level Validation . . . . . . . . . . . . . . . . . . . . . 9
4.3.2 Object-level Validation . . . . . . . . . . . . . . . . . . . . 9
4.3.3 Validator Functions . . . . . . . . . . . . . . . . . . . . . 9
4.4 Serializer Methods . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4.5 API Testing with Postman . . . . . . . . . . . . . . . . . . . . . 10
1
4.6 Sending Data from JavaScript . . . . . . . . . . . . . . . . . . . . 10
4.6.1 JSON Payload . . . . . . . . . . . . . . . . . . . . . . . . 10
4.6.2 FormData (Multipart) . . . . . . . . . . . . . . . . . . . . 11
4.7 Handling JSON Payload in Views . . . . . . . . . . . . . . . . . . 11
5 Django Admin Customization 12
5.1 Basic Admin Configuration . . . . . . . . . . . . . . . . . . . . . 12
5.2 Advanced Filtering . . . . . . . . . . . . . . . . . . . . . . . . . . 12
5.3 Permissions and Groups . . . . . . . . . . . . . . . . . . . . . . . 12
6 Third-Party APIs Integration 13
6.1 Common Integration Patterns . . . . . . . . . . . . . . . . . . . . 13
1 Models in Django
1.1 Applying Constraints in Django Models
Django provides several ways to enforce data integrity:
Constraint Description
unique=True Ensures field values are unique across table
null=False Database-level NULL constraint
blank=False Form validation for required fields
db index=True Creates database index for faster queries
choices Restricts values to predefined choices
validators Custom validation functions
db constraint Controls ForeignKey constraint creation
Table 1: Common Django Model Constraints
Example with multiple constraints:
1 from django . core . validators import MinLengthValidator ,
Rege xValidat or
2
3 class Student ( models . Model ) :
4 student_id = models . CharField (
5 max_length =10 ,
6 unique = True ,
7 validators =[
8 M i n L e n g t h V a l i d a t o r (10) ,
9 Rege xValidat or ( r ’ ^[ A - Z ]{2}\ d {8} $ ’)
10 ]
11 )
12 e nr ol lm e nt _d at e = models . DateField ( auto_now_add = True )
13 status = models . CharField (
14 max_length =20 ,
15 choices =[
16 ( ’ active ’ , ’ Active ’) ,
2
17 ( ’ suspended ’ , ’ Suspended ’) ,
18 ( ’ graduated ’ , ’ Graduated ’)
19 ],
20 default = ’ active ’
21 )
1.2 Relationships Between Tables and Fields
Django supports all standard database relationships:
• ForeignKey: Many-to-one relationship
– on delete=[Link] (default)
– on delete=[Link]
– on delete=[Link] NULL
– related name for reverse access
• ManyToManyField: Many-to-many relationship
– Automatic intermediate table
– Custom through model for extra fields
• OneToOneField: One-to-one relationship
– Often used for model inheritance
– Useful for extending user models
Example with all relationship types:
1 class Department ( models . Model ) :
2 name = models . CharField ( max_length =100)
3
4 class Professor ( models . Model ) :
5 name = models . CharField ( max_length =100)
6 department = models . ForeignKey (
7 Department ,
8 on_delete = models . CASCADE ,
9 related_name = ’ professors ’
10 )
11
12 class Course ( models . Model ) :
13 title = models . CharField ( max_length =200)
14 professors = models . M an yT oM a ny Fi el d ( Professor )
15 prerequisites = models . M a ny To Ma n yF ie l d ( ’ self ’ , symmetrical =
False )
16
17 class P r o f e s s o r P r o f i l e ( models . Model ) :
18 professor = models . OneToOneField (
19 Professor ,
20 on_delete = models . CASCADE ,
21 primary_key = True
22 )
23 o ff ic e_ l oc at io n = models . CharField ( max_length =50)
3
1.3 Model Methods and Query Optimization
Key methods for database operations:
1.3.1 Basic Methods
1 # Create and save
2 p = Product ( name = " Laptop " , price =999.99)
3 p . save () # Explicit save
4
5 # Get single object
6 try :
7 product = Product . objects . get ( id =1)
8 except Product . DoesNotExist :
9 # Handle missing object
1.3.2 QuerySet Methods
1 # Filtering
2 cheap _produc ts = Product . objects . filter (
3 price__lt =100 ,
4 in_stock = True
5 ) . exclude (
6 discontinued = True
7 )
8
9 # Complex lookups
10 from django . db . models import Q
11 products = Product . objects . filter (
12 Q ( price__lt =100) | Q ( category = ’ Electronics ’)
13 )
1.3.3 Optimization Methods
1 # select _related ( for ForeignKey )
2 orders = Order . objects . select_ related ( ’ customer ’) . all ()
3
4 # p r ef e t c h _ r e l a t e d ( for ManyToMany )
5 products = Product . objects . p r e f e t c h _ r e l a te d ( ’ categories ’) . all ()
6
7 # only () and defer () for partial loading
8 users = User . objects . only ( ’ username ’ , ’ email ’)
1.4 Migration in Django
Django’s migration system tracks model changes:
• makemigrations: Creates migration files
– --name for custom migration names
– --empty for empty migrations
4
• migrate: Applies migrations
– --fake for marking as run without executing
– --plan to show migration plan
• sqlmigrate: Shows SQL for migration
• showmigrations: Lists all migrations
Example data migration:
1 # Generated by mak emigrati ons -- empty
2 from django . db import migrations
3
4 def transfer_data ( apps , schema_editor ) :
5 OldModel = apps . get_model ( ’ myapp ’ , ’ OldModel ’)
6 NewModel = apps . get_model ( ’ myapp ’ , ’ NewModel ’)
7
8 for old in OldModel . objects . all () :
9 NewModel . objects . create (
10 new_field = old . old_field ,
11 # ... other field mappings
12 )
13
14 class Migration ( migrations . Migration ) :
15 dependencies = [( ’ myapp ’ , ’ p r e v i o u s _ m i g r a t i o n ’) ]
16
17 operations = [
18 migrations . RunPython ( transfer_data ) ,
19 ]
2 User Model for Validation
2.1 Creating User Profile with Extra Fields
Two recommended approaches:
2.1.1 Option 1: One-to-One Profile
1 from django . contrib . auth . models import User
2
3 class UserProfile ( models . Model ) :
4 user = models . OneToOneField (
5 User ,
6 on_delete = models . CASCADE ,
7 related_name = ’ profile ’
8 )
9 phone = models . CharField ( max_length =20)
10 address = models . TextField ()
11 birth_date = models . DateField ( null = True )
12
13 def __str__ ( self ) :
14 return f " { self . user . username } ’ s profile "
5
2.1.2 Option 2: Proxy Model
1 class CustomUser ( User ) :
2 class Meta :
3 proxy = True
4
5 def g e t _ f u l l _ a d d r e s s ( self ) :
6 return f " { self . profile . address } "
2.2 AbstractUser Model
The recommended way for complete customization:
1 from django . contrib . auth . models import AbstractUser
2 from django . db import models
3
4 class CustomUser ( AbstractUser ) :
5 # Add additional fields
6 phone_number = models . CharField ( max_length =15 , blank = True )
7 date_of_birth = models . DateField ( null = True , blank = True )
8 bio = models . TextField ( blank = True )
9 avatar = models . ImageField ( upload_to = ’ avatars / ’ , null = True )
10
11 # Custom methods
12 def get_sho rt_name ( self ) :
13 return self . username
14
15 # Required setup
16 R EQ UI RE D _F IE LD S = [ ’ email ’] # For c re a te su pe r us er
17
18 # settings . py
19 A UT H_ US E R_ MO DE L = ’ accounts . CustomUser ’
2.3 User Model and One-to-One Relationship
Best practices for profile extension: Coming Soon
3 Forms and Validation
3.1 ModelForm Concept
ModelForms bridge models and forms:
1 from django . forms import ModelForm
2 from . models import Article
3
4 class ArticleForm ( ModelForm ) :
5 class Meta :
6 model = Article
7 fields = [ ’ title ’ , ’ content ’ , ’ status ’]
8 labels = {
9 ’ title ’: ’ Article Title ’ ,
10 ’ status ’: ’ Publishing Status ’
6
11 }
12 help_texts = {
13 ’ content ’: ’ Markdown supported ’
14 }
15 widgets = {
16 ’ status ’: forms . Select ( choices =[
17 ( ’ draft ’ , ’ Draft ’) ,
18 ( ’ published ’ , ’ Published ’)
19 ])
20 }
3.2 Meta Class Configuration
The Meta class controls form behavior:
Option Description
model The model to use
fields List of fields to include
exclude List of fields to exclude
labels Custom field labels
help texts Custom help texts
error messages Custom error messages
widgets Custom widgets for fields
localized fields Fields to localize
Table 2: ModelForm Meta Options
3.3 Form Validation Techniques
Django provides multiple validation layers:
3.3.1 Field Validation
1 class R e g i s t r a t i o n F o r m ( forms . Form ) :
2 username = forms . CharField ( min_length =4)
3 email = forms . EmailField ()
4
5 def clean_u sername ( self ) :
6 username = self . cleaned_data [ ’ username ’]
7 if User . objects . filter ( username = username ) . exists () :
8 raise forms . Va l id at i on Er ro r ( " Username taken " )
9 return username
3.3.2 Form-wide Validation
1 def clean ( self ) :
2 cleaned_data = super () . clean ()
7
3 password = cleaned_data . get ( ’ password ’)
4 confirm = cleaned_data . get ( ’ c o nf i r m _ p a s s w o r d ’)
5
6 if password and confirm and password != confirm :
7 self . add_error ( ’ c o n f i r m _ p a s s w o r d ’ , " Passwords don ’t match " )
8
9 return cleaned_data
3.3.3 Validators
1 from django . core . validators import RegexVal idator
2
3 p ho ne _v a li da to r = Rege xValidat or (
4 r ’ ^\+?1?\ d {9 ,15} $ ’ ,
5 " Phone format : ’+999999999 ’ "
6 )
7
8 class ContactForm ( forms . Form ) :
9 phone = forms . CharField ( validators =[ p h on e_ va l id at or ])
4 Serialization
4.1 Creating Serializers
DRF serializers convert complex data types:
1 from rest_fra mework import serializers
2 from . models import Book , Author
3
4 class A u t h o r S e r i a l i z e r ( serializers . Mo d el Se ri a li ze r ) :
5 class Meta :
6 model = Author
7 fields = [ ’ id ’ , ’ name ’ , ’ nationality ’]
8
9 class Boo kSerial izer ( serializers . M o de lS er i al iz er ) :
10 author = Au t h o r S e r i a l i z e r ()
11
12 class Meta :
13 model = Book
14 fields = [ ’ id ’ , ’ title ’ , ’ author ’ , ’ p u b l i c a t i o n _ d a t e ’]
15 depth = 1 # Controls nested repre sentatio n
4.2 Nested Serializers
Handling complex relationships:
1 class Tr ac k Se ri al i ze r ( serializers . Mo de l Se ri al i ze r ) :
2 class Meta :
3 model = Track
4 fields = [ ’ order ’ , ’ title ’ , ’ duration ’]
5
6 class Al bu m Se ri al i ze r ( serializers . Mo de l Se ri al i ze r ) :
7 tracks = T ra ck S er ia li z er ( many = True )
8
8
9 class Meta :
10 model = Album
11 fields = [ ’ name ’ , ’ artist ’ , ’ tracks ’]
12
13 def create ( self , validat ed_data ) :
14 tracks_data = v alidated _data . pop ( ’ tracks ’)
15 album = Album . objects . create (** valida ted_dat a )
16
17 for track_data in tracks_data :
18 Track . objects . create ( album = album , ** track_data )
19
20 return album
4.3 Serializer Validation
Comprehensive validation approaches:
4.3.1 Field-level Validation
1 def validate _title ( self , value ) :
2 if len ( value ) < 5:
3 raise serializers . V al id a ti on Er r or (
4 " Title must be at least 5 characters "
5 )
6 return value
4.3.2 Object-level Validation
1 def validate ( self , data ) :
2 start = data . get ( ’ start_date ’)
3 end = data . get ( ’ end_date ’)
4
5 if start and end and start > end :
6 raise serializers . V al id a ti on Er r or (
7 " End date must be after start date "
8 )
9 return data
4.3.3 Validator Functions
1 from rest_fra mework . validators import Un iq u eV al id a to r
2
3 class P r o d u c t S e r i a l i z e r ( serializers . M od el S er ia li z er ) :
4 sku = serializers . CharField (
5 validators =[ Un iq ue V al id at o r ( queryset = Product . objects . all () )
]
6 )
9
4.4 Serializer Methods
Comming Soon
4.5 API Testing with Postman
Best practices for API testing:
• Request Types:
– GET for retrieval
– POST for creation
– PUT/PATCH for updates
– DELETE for removal
• Headers:
– Content-Type: application/json
– Authorization: Token/Bearer
• Environment Variables:
– Base URLs
– Auth tokens
• Test Scripts:
1 // Example Postman test
2 pm . test (" Status code is 200" , function () {
3 pm . response . to . have . status (200) ;
4 }) ;
5
6 pm . test (" Response has data " , function () {
7 var jsonData = pm . response . json () ;
8 pm . expect ( jsonData ) . to . have . property ( ’ data ’) ;
9 }) ;
10
4.6 Sending Data from JavaScript
AJAX requests with different formats:
4.6.1 JSON Payload
1 fetch ( ’/ api / books / ’ , {
2 method : ’ POST ’ ,
3 headers : {
4 ’ Content - Type ’: ’ application / json ’ ,
5 ’X - CSRFToken ’: getCookie ( ’ csrftoken ’)
6 },
7 body : JSON . stringify ({
10
8 title : " New Book " ,
9 author : 1
10 })
11 })
12 . then ( response = > response . json () )
13 . then ( data = > console . log ( data ) ) ;
4.6.2 FormData (Multipart)
1 const formData = new FormData () ;
2 formData . append ( ’ title ’ , ’ New Book ’) ;
3 formData . append ( ’ cover_image ’ , fileInput . files [0]) ;
4
5 fetch ( ’/ api / books / ’ , {
6 method : ’ POST ’ ,
7 body : formData
8 }) ;
4.7 Handling JSON Payload in Views
Processing different content types:
1 from django . views . decorators . csrf import csrf_exempt
2 from django . http import JsonResponse
3 import json
4
5 @csrf_exempt
6 def a pi _c re a te _b oo k ( request ) :
7 if request . method == ’ POST ’:
8 try :
9 # Handle JSON
10 if request . content_type == ’ application / json ’:
11 data = json . loads ( request . body )
12
13 # Handle form data
14 else :
15 data = request . POST
16
17 # Process data
18 book = Book . objects . create (
19 title = data [ ’ title ’] ,
20 author_id = data [ ’ author_id ’]
21 )
22
23 return JsonResponse ({
24 ’ status ’: ’ success ’ ,
25 ’ id ’: book . id
26 })
27
28 except Exception as e :
29 return JsonResponse (
30 { ’ error ’: str ( e ) } ,
31 status =400
32 )
11
5 Django Admin Customization
5.1 Basic Admin Configuration
Essential admin customizations:
1 from django . contrib import admin
2 from . models import Product
3
4 @admin . register ( Product )
5 class ProductAdmin ( admin . ModelAdmin ) :
6 list_display = ( ’ name ’ , ’ price ’ , ’ stock ’ , ’ created_at ’)
7 list_filter = ( ’ category ’ , ’ is_active ’)
8 search_fields = ( ’ name ’ , ’ description ’)
9 ordering = ( ’ - created_at ’ ,)
10 date _hierarc hy = ’ created_at ’
11 r ea do nl y _f ie ld s = ( ’ sku ’ ,)
12 fieldsets = (
13 ( None , {
14 ’ fields ’: ( ’ name ’ , ’ description ’)
15 }) ,
16 ( ’ Pricing ’ , {
17 ’ fields ’: ( ’ price ’ , ’ discount ’) ,
18 ’ classes ’: ( ’ collapse ’ ,)
19 })
20 )
5.2 Advanced Filtering
Custom filters and search:
1 class P r i c e R a n g e F i l t e r ( admin . S i m p l e L i s t F i l t er ) :
2 title = ’ price range ’
3 para meter_na me = ’ price ’
4
5 def lookups ( self , request , model_admin ) :
6 return (
7 ( ’ 0 -50 ’ , ’ Cheap ( $0 - $50 ) ’) ,
8 ( ’ 50 -100 ’ , ’ Mid ( $50 - $100 ) ’) ,
9 ( ’ 100 - ’ , ’ Expensive ( $100 +) ’)
10 )
11
12 def queryset ( self , request , queryset ) :
13 if self . value () == ’ 0 -50 ’:
14 return queryset . filter ( price__lte =50)
15 if self . value () == ’ 50 -100 ’:
16 return queryset . filter ( price__gt =50 , price__lte =100)
17 if self . value () == ’ 100 - ’:
18 return queryset . filter ( price__gt =100)
19
20 class ProductAdmin ( admin . ModelAdmin ) :
21 list_filter = ( PriceRangeFilter ,)
5.3 Permissions and Groups
Managing access control:
12
1 # models . py - Custom permissions
2 class Article ( models . Model ) :
3 class Meta :
4 permissions = [
5 ( ’ can_publish ’ , ’ Can publish articles ’) ,
6 ( ’ can_edit_all ’ , ’ Can edit all articles ’)
7 ]
8
9 # admin . py - Group - based permissions
10 from django . contrib . auth . models import Group
11
12 class C u s t o m G r o u p A d m i n ( admin . ModelAdmin ) :
13 f i l t e r _ h o r i z o n t a l = [ ’ permissions ’]
14
15 admin . site . unregister ( Group )
16 admin . site . register ( Group , C us t o m G r o u p A d m i n )
6 Third-Party APIs Integration
6.1 Common Integration Patterns
Comming soon
13