0% found this document useful (0 votes)
4 views5 pages

Django Notes

The document provides comprehensive exam preparation notes for Django, covering key topics such as project structure, models and ORM, views, templates, forms, URL routing, database migrations, authentication, and middleware. It outlines the features of Django, including its MTV architecture and built-in functionalities for rapid web development. Each section includes code examples and explanations to aid understanding of Django's capabilities and best practices.

Uploaded by

mahhamalik5850
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views5 pages

Django Notes

The document provides comprehensive exam preparation notes for Django, covering key topics such as project structure, models and ORM, views, templates, forms, URL routing, database migrations, authentication, and middleware. It outlines the features of Django, including its MTV architecture and built-in functionalities for rapid web development. Each section includes code examples and explanations to aid understanding of Django's capabilities and best practices.

Uploaded by

mahhamalik5850
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

DJANGO PYTHON

Comprehensive Exam Preparation Notes


Bachelor of Science (BSc)

TABLE OF CONTENTS
1. 1. Introduction to Django
2. 2. Project Structure and Setup
3. 3. Models and ORM
4. 4. Views and CBVs
5. 5. Templates
6. 6. Forms
7. 7. URL Routing
8. 8. Database and Migrations
9. 9. Authentication and Authorization
10. 10. Middleware

1. INTRODUCTION TO DJANGO
What is Django?
Django is a high-level, open-source Python web framework that encourages rapid development
and clean, pragmatic design. It was created in 2003 and is maintained by the Django Software
Foundation.
Key Features of Django:
• ORM (Object-Relational Mapping) for database operations
• Built-in admin interface
• URL routing system
• Template engine for dynamic HTML generation
• Authentication and authorization system
• Security features (CSRF protection, SQL injection prevention)
• Scalability and flexibility
MTV Architecture:
Django follows the Model-Template-View (MTV) architecture, a variant of MVC:
Component Description
Model Represents the data structure and database
logic
Template Represents the presentation layer
(HTML/CSS)
View Contains the business logic and processes
user requests
2. PROJECT STRUCTURE AND SETUP
Creating a Django Project:
11. Step 1: Install Django
pip install django
12. Step 2: Create a Django Project
django-admin startproject myproject
13. Step 3: Create an Application
python [Link] startapp myapp

Project Directory Structure:


• myproject/
◦ [Link] - Command-line utility for project tasks
◦ myproject/ (Inner directory)
◦ __init__.py - Package initializer
◦ [Link] - Project configuration
◦ [Link] - URL routing configuration
◦ [Link] - ASGI server entry point
◦ [Link] - WSGI server entry point

3. MODELS AND ORM


Understanding Models:
A model is a Python class that represents a database table. Each attribute of the model
represents a database field.
Example Model:
from [Link] import models class User([Link]): name =
[Link](max_length=100) email = [Link]() age =
[Link]() created_at = [Link](auto_now_add=True)
Common Field Types:
Field Type Description
CharField String field with maximum length
TextField Large text field
IntegerField Integer field
FloatField Floating-point number
DateField Date field
DateTimeField Date and time field
BooleanField True/False field
EmailField Email validation field
URLField URL validation field
ForeignKey One-to-many relationship
ManyToManyField Many-to-many relationship

ORM Queries:
Django ORM provides a Pythonic way to query databases without writing SQL:
# Create user = [Link](name='John', email='john@[Link]') # Read user =
[Link](id=1) users = [Link]() users = [Link](age__gte=18) #
Update [Link] = 'Jane' [Link]() # Delete [Link]()

4. VIEWS AND CLASS-BASED VIEWS


Function-Based Views (FBV):
A view is a Python function that takes a web request and returns a response.
from [Link] import render from [Link] import HttpResponse from .models import
User def user_list(request): users = [Link]() return render(request, '[Link]',
{'users': users})

Class-Based Views (CBV):


Class-based views are more structured and reusable than function-based views.
from [Link] import View from [Link] import ListView from .models import
User class UserListView(ListView): model = User template_name = '[Link]'
context_object_name = 'users' paginate_by = 10
Common Generic Views:
View Purpose
ListView Display a list of objects
DetailView Display a single object
CreateView Create a new object
UpdateView Update an existing object
DeleteView Delete an object

5. TEMPLATES
Django Template Language:
Templates are HTML files with Django template tags and filters for dynamic content generation.
Template Syntax:
• {{ variable }} - Output variable
• {% tag %} - Execute template tag
• {# comment #} - Template comment
Example Template:
<h1>Users List</h1> {% for user in users %} <p>{{ [Link] }} - {{ [Link] }}</p> {%
empty %} <p>No users found.</p> {% endfor %}
Template Inheritance:
Base template ([Link]): <!DOCTYPE html> <html> <head> {% block title %}{% endblock
%} </head> <body> {% block content %}{% endblock %} </body> </html> Child template
([Link]): {% extends '[Link]' %} {% block title %}Users{% endblock %} {% block content
%} <h1>Users</h1> {% endblock %}

6. FORMS
Django Forms:
Forms are used to collect user input and validate data on the server side.
Creating a Form:
from django import forms from .models import User class UserForm([Link]):
class Meta: model = User fields = ['name', 'email', 'age']
Form Validation:
if form.is_valid(): [Link]() else: errors = [Link]

7. URL ROUTING
URL Configuration:
from [Link] import path from . import views urlpatterns = [ path('users/', views.user_list,
name='user_list'), path('users/<int:id>/', views.user_detail, name='user_detail'), ]
URL Parameters:
• <int:id> - Integer parameter
• <str:name> - String parameter
• <slug:slug> - Slug parameter

8. DATABASE AND MIGRATIONS


Migrations:
Migrations are Django's way of version-controlling your database schema.
Creating and Running Migrations:
# Create migration python [Link] makemigrations # Apply migration python [Link]
migrate # View migration status python [Link] showmigrations
9. AUTHENTICATION AND AUTHORIZATION
Built-in User Model:
Django provides a built-in User model for authentication.
Authentication Examples:
from [Link] import authenticate, login from [Link] import User
# Create user user = [Link].create_user('john', 'john@[Link]', 'password') #
Authenticate user = authenticate(username='john', password='password') # Login
login(request, user)
Permission Decorators:
from [Link] import login_required @login_required def
user_profile(request): return render(request, '[Link]')

10. MIDDLEWARE
Understanding Middleware:
Middleware is a series of hooks/filters for processing requests and responses globally.
Common Middleware:
• SecurityMiddleware - Adds security headers
• SessionMiddleware - Manages user sessions
• AuthenticationMiddleware - Associates users with requests
• CsrfViewMiddleware - CSRF protection
Creating Custom Middleware:
class MyMiddleware: def __init__(self, get_response): self.get_response =
get_response def __call__(self, request): response = self.get_response(request)
return response

END OF NOTES

You might also like