Django Notes
Django Notes
aiming for answers appropriate for 6-10 mark questions in college exams.
Q: Explain Python collections and its container data types. Provide examples.
A: Python collections module provides specialized container data types, enhancing Python's
standard data structures. Key container data types include:
Q: What is Tkinter, and how is it used to create GUI applications in Python? Provide an
example.
A: Tkinter is Python’s standard library for GUI development. It provides a fast and easy way to
build graphical user interfaces.
Example:
import tkinter as tk
Q: Explain web scraping and the role of Scrapy in it. Provide an example.
A: Web scraping is the process of extracting data from websites using automated scripts. Scrapy
is a Python framework designed specifically for large-scale web scraping.
Example:
import scrapy
class QuotesSpider(scrapy.Spider):
name = 'quotes'
start_urls = ['http://quotes.toscrape.com']
1. Client Request: A client sends an HTTP request to the server, specifying the resource
and method (GET, POST, etc.).
2. Server Processing: The server processes the request, executes the required logic, and
interacts with the database if needed.
3. Response Creation: The server generates an HTTP response (status code, headers, and
content).
4. Response Delivery: The response is sent back to the client, completing the cycle.
Diagram:
MVC (Model-View-Controller):
o Model: Manages data and business logic.
o View: Displays data to users.
o Controller: Handles user input and updates the Model and View accordingly.
MVT (Model-View-Template): Django adapts MVC as MVT.
o Model: Manages data.
o View: Contains business logic (acts as Controller).
o Template: Handles presentation logic (acts as View).
Django Architecture:
Django processes requests in the following way:
Base Template:
Child Template:
{% block content %}
<h1>Welcome to My Site</h1>
{% endblock %}
class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response
Features:
Example:
views.py:
def logout_view(request):
logout(request)
return redirect('login')
Example:
forms.py:
class RegistrationForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput)
confirm_password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model = User
fields = ['username', 'email', 'password']
def clean(self):
cleaned_data = super().clean()
password = cleaned_data.get("password")
confirm_password = cleaned_data.get("confirm_password")
if password != confirm_password:
raise forms.ValidationError("Passwords do not match")
views.py:
def register(request):
if request.method == "POST":
form = RegistrationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login')
else:
form = RegistrationForm()
return render(request, 'register.html', {'form': form})
Example:
If a model is defined:
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
Running makemigrations and migrate will create a corresponding database table for Book.
Example:
Custom middleware that adds a custom header:
middleware.py:
class AddHeaderMiddleware:
def __init__(self, get_response):
self.get_response = get_response
MIDDLEWARE = [
...,
'myapp.middleware.AddHeaderMiddleware',
]
Example:
Using the low-level cache API:
Benefits:
Q: What is the purpose of hosting a Git repository? Name some popular hosting platforms.
A: Hosting a Git repository enables developers to store, manage, and collaborate on projects. It
provides version control, backup, and easy sharing capabilities.
Popular Platforms:
1. GitHub: Offers public and private repositories with features like pull requests, issues,
and GitHub Actions.
2. GitLab: Provides CI/CD tools and supports DevOps workflows.
3. Bitbucket: Integrated with Atlassian tools like Jira and Trello.
Steps to Host a Repository on GitHub:
16. WSGI
Purpose:
Acts as a bridge between the web server (e.g., Nginx) and the Python application (e.g.,
Django).
Handles requests and responses.
Key Features:
Platform-independent.
Supports multiple frameworks and servers.
Example:
Django’s WSGI application is defined in the wsgi.py file:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
application = get_wsgi_application()
Syntax:
@decorator_name
def function_name():
pass
Example:
Logging function execution:
def log_decorator(func):
def wrapper(*args, **kwargs):
print(f"Function {func.__name__} is being executed")
return func(*args, **kwargs)
return wrapper
@log_decorator
def greet(name):
print(f"Hello, {name}")
greet("Deepanshu")
Output:
MVT in Django:
Example:
1. urls.py:
2. from django.urls import path
3. from . import views
4.
5. urlpatterns = [
6. path('', views.home, name='home'),
7. path('about/', views.about, name='about'),
8. ]
9. views.py:
10. from django.shortcuts import render
11.
12. def home(request):
13. return render(request, 'home.html')
14.
15. def about(request):
16. return render(request, 'about.html')
Template System:
Template Inheritance:
Example:
1. base.html:
2. <html>
3. <head><title>{% block title %}My Site{% endblock %}</title></head>
4. <body>
5. <header>Header Section</header>
6. <main>{% block content %}{% endblock %}</main>
7. <footer>Footer Section</footer>
8. </body>
9. </html>
10. home.html:
11. {% extends 'base.html' %}
12. {% block title %}Home{% endblock %}
13. {% block content %}
14. <h1>Welcome to My Site</h1>
15. {% endblock %}
Covered earlier.
Q: How do you handle static files when deploying a Django app on Heroku?
A:
Steps:
1. Install whitenoise:
2. pip install whitenoise
3. Add whitenoise to middleware in settings.py:
4. MIDDLEWARE = [
5. 'whitenoise.middleware.WhiteNoiseMiddleware',
6. ...
7. ]
8. Define STATIC_ROOT in settings.py:
9. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
10. Collect static files:
11. python manage.py collectstatic
Steps:
1. Install Gunicorn:
2. pip install gunicorn
3. Create a Procfile for Heroku:
4. web: gunicorn myproject.wsgi
5. Run Gunicorn locally:
6. gunicorn myproject.wsgi
7. Deploy to Heroku following the steps in Heroku Deployment.
Here are the answers to the given questions, structured for a 6-mark explanation:
First Image
1. Install Flask:
o Install Flask using pip: pip install flask.
2. Create Project Directory:
o Create a folder and a Python script (e.g., app.py).
3. Import Flask:
o Start the script with from flask import Flask.
4. Initialize the Flask App:
o Define the app: app = Flask(__name__).
5. Create Routes:
o Use @app.route('/') to define the home page route.
o Add functions to handle requests.
6. Run the App:
o Add if __name__ == '__main__': app.run(debug=True) to start the server.
1. MVT Architecture:
o Model-View-Template structure for efficient development.
2. Admin Interface:
o Built-in admin panel for easy management.
3. ORM (Object-Relational Mapping):
o Simplifies database operations with Python objects.
4. Security:
o Mitigates threats like XSS and SQL injection by default.
5. Scalability:
o Designed to handle large-scale applications efficiently.
6. Community and Libraries:
o Extensive community support and reusable libraries.
3-d. Describe the process when a typical Django website gets a request.
Frameworks:
Second Image
1. Zappa:
o Used to deploy Flask/Django apps on AWS Lambda.
o Key features: Serverless architecture, scalability, cost-efficient.
2. Flask:
o Micro-framework for Python with minimal setup.
o Ideal for lightweight applications.
url = 'http://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.text)
1. Model:
o Represents the data structure.
2. View:
o Handles business logic.
3. Template:
o Manages HTML rendering.
o Django’s MVT is similar to MVC.
1. Components Independence:
o Each component (Model, View, Template) operates independently.
2. Flexibility:
o Easily replaceable or customizable components.
1. Import Forms:
o from django import forms.
2. Create Form Class:
3. class MyForm(forms.Form):
4. email = forms.EmailField()
3-f. Discuss the ways you can set up the database in Django.
1. Modify settings.py:
o Configure DATABASES for MySQL, PostgreSQL, SQLite, etc.
2. Migrate Models:
o Use python manage.py migrate.
1. Slack Bots.
2. E-commerce Platforms.
3. Data Dashboards.
Here are detailed answers to the questions:
Tkinter is a standard Python library for creating Graphical User Interface (GUI) applications. It
provides a variety of widgets such as buttons, labels, text boxes, and menus to build interactive
desktop applications.
Features:
Platform-independent.
Supports various widgets.
Event-driven programming.
Easy to use with a wide range of customizations.
Example:
import tkinter as tk
# Create a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()
# Create a button
def on_button_click():
label.config(text="Button Clicked!")
Explanation:
a) ChainMap:
Part of the collections module.
Combines multiple dictionaries into a single view.
Changes in the original dictionaries reflect in the ChainMap.
Example:
b) Counter:
Example:
c) Deque:
Double-ended queue.
Supports O(1) operations for appending and popping elements from both ends.
Example:
5-a. What are the various files that are created with a Django Project? (CO2)
1. manage.py:
A command-line utility to interact with the project.
2. settings.py:
Contains all the settings for the project like databases, middleware, and installed apps.
3. urls.py:
Maps URLs to views.
4. wsgi.py and asgi.py:
Entry points for WSGI and ASGI servers.
5. models.py:
Contains database models.
6. views.py:
Contains business logic for handling requests and responses.
7. templates/:
Directory for storing HTML templates.
8. static/:
Directory for static files like CSS, JS, and images.
Django is a high-level Python web framework that promotes rapid development and clean
design.
Features:
1. MTV Architecture:
Follows the Model-Template-View (MTV) pattern for organizing code.
2. Automatic Admin Interface:
Built-in admin panel to manage application data.
3. ORM:
Maps Python objects to database tables seamlessly.
4. Scalability:
Handles high traffic.
5. Security:
Protects against SQL injection, XSS, and CSRF attacks.
6-a. Explain the authentication and authorization system in Django. Discuss the
difference between them. (CO3)
Authentication:
Authorization:
Difference:
Aspect Authentication Authorization
Definition Validates identity Manages access rights
Process Login system Permission system
Role Who you are What you can do
Example in Django:
@login_required
@permission_required('app.view_data')
def view_data(request):
# Logic here
pass
7-a. Explain how you send data from view to template. (CO4)
Process:
Example:
def home(request):
context = {'name': 'Deepanshu', 'age': 25}
return render(request, 'home.html', context)
Template (home.html):
Output:
Name: Deepanshu
Age: 25
1. Install Django:
2. pip install django
3. Create Project:
4. django-admin startproject myproject
5. Create App:
6. python manage.py startapp myapp
7. Define Models:
Write models in models.py.
8. Migrate Database:
9. python manage.py makemigrations
10. python manage.py migrate
11. Write Views:
Define views in views.py.
12. Setup URLs:
Map URLs in urls.py.
13. Add Templates:
Create HTML templates.
14. Run Server:
15. python manage.py runserver
4-a. Explain Quixote web framework. Define core principle of Quixote web
framework in your words. (CO1)
Answer:
Quixote is a lightweight Python web framework designed for building dynamic websites. It is
focused on simplicity and flexibility.
Core Principles:
1. Simplicity: The framework is minimalistic, focusing on allowing developers to write pure Python
code for web applications.
2. Flexibility: It avoids enforcing strict conventions, enabling developers to structure their
applications freely.
3. Code Over Configuration: Unlike other frameworks, Quixote relies heavily on Python code
rather than configuration files for functionality.
Example:
def hello_world():
return "Hello, Quixote!"
publisher = Publisher(hello_world)
4-b. Explain features of BeautifulSoup in your words with the help of example.
(CO1)
Answer:
BeautifulSoup is a Python library used for web scraping purposes to extract data from HTML
and XML files. It parses the document into a navigable tree structure.
Features of BeautifulSoup:
Example:
html = """
<html>
<head><title>Sample Website</title></head>
<body>
<h1>Welcome to BeautifulSoup</h1>
<p class="intro">This is a tutorial for web scraping.</p>
</body>
</html>
"""
print(f"Title: {title}")
print(f"Introduction: {intro}")
Output:
5-a. Explain why Django is better than Flask. Explain the key difference between
them. (CO2)
Answer:
Django's Advantages over Flask:
1. Full-stack Framework: Django comes with built-in features for handling authentication, ORM,
and admin panels, whereas Flask requires third-party extensions.
2. Scalability: Django supports scalability for large-scale applications with its modular design.
3. Security: Django has in-built protections against SQL injection, CSRF, and XSS attacks.
4. Admin Interface: Django includes a fully customizable admin interface for managing application
data.
Key Differences:
5-b. Write all steps to create your first Django model Student with fields like roll no,
name, class, and department. (CO2)
Answer:
Steps to create a Django model:
6-a. Create a registration form using Django and add email configuration settings.
(CO3)
Answer:
Steps:
Answer:
1. SQL Injection:
o Issue: Exploits user input to execute malicious SQL queries.
o Solution: Use Django ORM to handle database queries.
3. CSRF Attacks:
o Issue: Forces users to execute unwanted actions on a website.
o Solution: Enable CSRF middleware and use {% csrf_token %} in forms.
4. Clickjacking:
o Issue: Embedding website content into a malicious website.
o Solution: Use X-Frame-Options header.
7-a. Explain request-response life cycle of Django with diagram and code. (CO4)
Answer:
Diagram:
Code Example:
def sample_view(request):
return HttpResponse("Hello, this is a response!")
7-b. Describe the concept of Database Migration in Django and how to fetch data
from the database. (CO4)
Answer:
Database Migration:
Migration is the process of propagating changes made to the Django models into the database
schema. It allows developers to manage database changes incrementally without losing existing
data.
4. Apply Migrations:
5. python manage.py migrate
Example:
# models.py
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
department = models.CharField(max_length=100)
def student_list(request):
students = Student.objects.all() # Fetch all records
return render(request, 'students.html', {'students': students})
Answer:
Heroku and AWS are cloud platforms, but they differ in complexity and use cases.
1. Heroku:
o Simpler Use Case: Heroku is a Platform-as-a-Service (PaaS) that simplifies application
deployment.
o Ease of Use: Ideal for small to medium applications, rapid prototyping, and beginner
developers.
o Abstracted Infrastructure: Users do not manage servers directly.
Example Use Case: A startup deploying a simple web application with limited
customization.
2. AWS:
o Scalable and Flexible: AWS offers Infrastructure-as-a-Service (IaaS) and PaaS solutions,
giving more control over infrastructure.
o Wide Range of Services: Includes EC2, S3, Lambda, and more for large-scale, enterprise-
level projects.
o Customization and Complexity: Requires knowledge of networking, scaling, and
configuration.
Justification: Use Heroku for ease of deployment and AWS for advanced configurations and
scalability.
Answer:
WSGI (Web Server Gateway Interface):
WSGI is a specification for Python web applications to communicate with web servers. It
bridges the gap between a Python application and a web server.
Gunicorn:
Gunicorn (Green Unicorn) is a WSGI HTTP server that serves Python web applications
efficiently.
1. Install Gunicorn:
2. pip install gunicorn
5. Deployment: Use Gunicorn behind a reverse proxy like Nginx for production.
Advantages of Gunicorn: