0% found this document useful (0 votes)
2 views4 pages

Django Basics Notes

Django is a high-level Python web framework designed for rapid development and security, featuring an MTV architecture and built-in admin panel. The document provides a comprehensive guide on installing Django, setting up projects and apps, and handling views, URLs, and HTTP requests. It also covers error handling and advanced URL matching using regular expressions.

Uploaded by

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

Django Basics Notes

Django is a high-level Python web framework designed for rapid development and security, featuring an MTV architecture and built-in admin panel. The document provides a comprehensive guide on installing Django, setting up projects and apps, and handling views, URLs, and HTTP requests. It also covers error handling and advanced URL matching using regular expressions.

Uploaded by

shekharshikarwar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 4

■ Django Basics – Complete Detailed Notes

1. Introduction to Django
----------------------------
Django is a high-level Python web framework that encourages rapid development, clean design,
and strong security.
It is widely used to create dynamic and scalable web applications.

Key Features:
- MTV (Model–Template–View) architecture.
- Built-in Admin Panel for managing database objects.
- ORM (Object Relational Mapper) for database operations using Python instead of SQL.
- Security: CSRF protection, SQL injection prevention, authentication system.
- Scalability: used by companies like Instagram, Pinterest.

2. Installing Python and Django


--------------------------------
Step 1: Install Python
> python --version
Download from: python.org

Step 2: Install Virtual Environment (isolates dependencies per project)


> python -m venv myenv
Activate:
On Windows: myenv\Scripts\activate
On Mac/Linux: source myenv/bin/activate

Step 3: Install Django


> pip install django
Verify installation:
> django-admin --version

3. Setting up a Project in Editor (VS Code Recommended)


--------------------------------------------------------
- Install VS Code.
- Install extensions: Python, Django (for syntax highlighting).
- Open your project folder in VS Code.
- Use integrated terminal for Django commands.

4. Projects and Apps Overview


-------------------------------
- Project: The entire website configuration (settings, database, URLs).
- App: A component/module inside project that handles specific tasks.

Analogy:
Project = College, Apps = Departments (CSE, Mechanical, Civil)

5. Project Structure
---------------------
After: django-admin startproject myproject

myproject/
manage.py
myproject/
__init__.py
settings.py
urls.py
asgi.py
wsgi.py
File Roles:
- manage.py → Command-line tool to manage/run project.
- __init__.py → Marks folder as Python package.
- settings.py → Configurations (DB, apps, middleware, security).
- urls.py → URL routing system.
- asgi.py/wsgi.py → Deployment entry points.

6. Creating Your First Project


-------------------------------
Commands:
> django-admin startproject myproject
> cd myproject
> python manage.py runserver

Visit: http://127.0.0.1:8000/ → Django Welcome Page (rocket ■).

7. Django-admin & manage.py Commands


-------------------------------------
Common django-admin commands:
- startproject projectname → Creates project.
- help → Shows available commands.

Common manage.py commands:


- runserver → Runs development server.
- startapp appname → Creates a new app.
- makemigrations → Prepares DB changes.
- migrate → Applies DB changes.
- createsuperuser → Create admin user.
- shell → Opens Python shell with Django loaded.

8. App Structure
-----------------
After: python manage.py startapp home

home/
admin.py
apps.py
migrations/
__init__.py
models.py
tests.py
views.py

File Roles:
- admin.py → Register models for admin panel.
- apps.py → App configuration.
- migrations/ → Database migration files.
- models.py → Database structure via Python classes.
- tests.py → Unit tests.
- views.py → Business logic (request → response).

9. Creating an App (Step-by-Step)


---------------------------------
1. Create app:
> python manage.py startapp home
2. Register app in settings.py → INSTALLED_APPS.
3. Define a view in home/views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Hello Shekhar! Welcome to Django ■")
4. Create home/urls.py and connect:
from django.urls import path
from . import views
urlpatterns = [ path('', views.index, name='index'), ]
5. Connect in project urls.py:
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
]
Run server → http://127.0.0.1:8000/ → Output: Hello Shekhar!

10. Views in Django


---------------------
A view is a Python function or class that takes a request and returns a response.

Example:
from django.http import HttpResponse
def home(request):
return HttpResponse("Hello World!")

11. Mapping Views to URLs


---------------------------
Project urls.py:
from django.urls import path
from myApp import views
urlpatterns = [ path('', views.home, name='home') ]

12. Views with Logic


----------------------
Example:
def add_numbers(request):
x, y = 5, 10
return HttpResponse(f"Sum = {x+y}")

URL:
path('add/', views.add_numbers)

13. HTTP Requests in Django


-----------------------------
request.method → GET/POST
request.GET → Query params (?name=Shekhar)
request.POST → Form data

Example:
def greet(request):
name = request.GET.get('name', 'Guest')
return HttpResponse(f"Hello {name}!")

URL:
path('greet/', views.greet)

14. Responses in Django


-------------------------
- HttpResponse: Plain text/HTML response.
- JsonResponse: JSON data for APIs.

Example:
def api_data(request):
return JsonResponse({"id": 1, "name": "Shekhar"})
15. Dynamic URLs & Params
---------------------------
Example:
def user_profile(request, user_id):
return HttpResponse(f"User ID: {user_id}")

URL:
path('user//', views.user_profile)

Types of Converters:
- int → integer
- str → string
- slug → slug format
- path → full path

16. Regular Expressions in URLs


--------------------------------
Use re_path for regex based matching.

Example:
re_path(r'^articles/(?P[0-9]{4})/$', views.article)

17. Error Handling


-------------------
Custom error pages:
def page_not_found(request, exception):
return render(request, '404.html', status=404)

def server_error(request):
return render(request, '500.html', status=500)

urls.py:
handler404 = 'myApp.views.page_not_found'
handler500 = 'myApp.views.server_error'

18. Assignment Implementation


-------------------------------
View with Query Params:
URL: /info/?name=Ajay&age;=22&city;=Delhi
Output: "Hello, my name is Ajay. I am 22 years old and live in Delhi."

Regex Based View:


URL: /product/mobile123/
Output: "You requested product mobile with ID 123"

Regex ensures product_name = alphabets, product_id = digits.

■ Summary
Views = Functions/classes → responses
URLs = Map paths to views
Requests = method + data
Responses = text, HTML, JSON
Params = dynamic or ?query=params
Regex = advanced URL matching
Error Handling = custom 404/500

You might also like