0% found this document useful (0 votes)
15 views29 pages

Django Notes

The document provides a comprehensive overview of various topics related to Python programming, including collections, Tkinter for GUI applications, web scraping with Scrapy, and the Request-Response life cycle in web applications. It also covers Django's architecture, template inheritance, CRUD operations, middleware, authentication, user registration, database migrations, caching, deployment on Heroku, Git repository hosting, WSGI, and decorators. Each section includes questions and detailed answers, along with code examples to illustrate the concepts.
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)
15 views29 pages

Django Notes

The document provides a comprehensive overview of various topics related to Python programming, including collections, Tkinter for GUI applications, web scraping with Scrapy, and the Request-Response life cycle in web applications. It also covers Django's architecture, template inheritance, CRUD operations, middleware, authentication, user registration, database migrations, caching, deployment on Heroku, Git repository hosting, WSGI, and decorators. Each section includes questions and detailed answers, along with code examples to illustrate the concepts.
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
You are on page 1/ 29

Here’s a structured set of possible questions and their answers based on the topics you’ve listed,

aiming for answers appropriate for 6-10 mark questions in college exams.

1. Collections - Container Data Types

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:

1. Counter: Used for counting hashable objects.


2. from collections import Counter
3. data = Counter('mississippi')
4. print(data) # Output: Counter({'i': 4, 's': 4, 'p': 2, 'm': 1})
5. deque: Double-ended queue allowing append/pop operations from both ends efficiently.
6. from collections import deque
7. dq = deque([1, 2, 3])
8. dq.appendleft(0)
9. print(dq) # Output: deque([0, 1, 2, 3])
10. defaultdict: Provides default values for missing keys.
11. from collections import defaultdict
12. dd = defaultdict(int)
13. dd['a'] += 1
14. print(dd['a']) # Output: 1
15. print(dd['b']) # Output: 0
16. OrderedDict: Maintains the order of key insertion.
17. from collections import OrderedDict
18. od = OrderedDict()
19. od['a'] = 1
20. od['b'] = 2
21. print(od) # Output: OrderedDict([('a', 1), ('b', 2)])
22. namedtuple: Creates tuple subclasses with named fields.
23. from collections import namedtuple
24. Point = namedtuple('Point', ['x', 'y'])
25. p = Point(10, 20)
26. print(p.x, p.y) # Output: 10 20

2. Tkinter - GUI Applications

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.

Steps to create a GUI application:

1. Import the Tkinter module.


2. Create the main window.
3. Add widgets (e.g., labels, buttons, text boxes).
4. Use mainloop() to run the application.

Example:

import tkinter as tk

# Create main window


root = tk.Tk()
root.title("Sample GUI")

# Add label and button


label = tk.Label(root, text="Hello, Tkinter!")
label.pack()

button = tk.Button(root, text="Click Me", command=root.quit)


button.pack()

# Run the application


root.mainloop()

3. Web Scraping and Scrapy

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.

Key Features of Scrapy:

1. High-performance scraping and web crawling.


2. Built-in support for handling requests, parsing HTML, and managing output.
3. Asynchronous network requests for better speed.

Example:

import scrapy

class QuotesSpider(scrapy.Spider):
name = 'quotes'
start_urls = ['http://quotes.toscrape.com']

def parse(self, response):


for quote in response.css('div.quote'):
yield {
'text': quote.css('span.text::text').get(),
'author': quote.css('span small.author::text').get(),
}

4. Request-Response Life Cycle


Q: Explain the Request-Response life cycle in a web application.
A: The Request-Response life cycle refers to how client-server communication takes place in
web applications:

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:

Client (Browser) → HTTP Request → Server → Process → Response → Client

5. Django: MVC and MVT Architecture

Q: Differentiate between MVC and MVT in Django. Explain Django’s architecture.


A:

 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:

1. Request: A user sends a request via URL.


2. URLs.py: Maps the URL to the appropriate view.
3. View: Executes the logic and interacts with the Model.
4. Model: Fetches or modifies data in the database.
5. Template: Renders the data into an HTML response.

6. Django Template and Template Inheritance

Q: Explain Django templates and template inheritance with an example.


A:
Django templates define how data is presented in the HTML structure. Templates can use
inheritance to avoid duplicating code across pages.

Base Template:

<!-- base.html -->


<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>Site Header</header>
{% block content %}{% endblock %}
<footer>Site Footer</footer>
</body>
</html>

Child Template:

<!-- home.html -->


{% extends 'base.html' %}

{% block title %}Home Page{% endblock %}

{% block content %}
<h1>Welcome to My Site</h1>
{% endblock %}

7. CRUD Operations in Django

Q: Explain CRUD operations with examples in Django.


A:
CRUD (Create, Read, Update, Delete) are core database operations in web applications.

1. Create: Add a new record to the database.


2. from myapp.models import Post
3. new_post = Post(title="New Post", content="Post content")
4. new_post.save()
5. Read: Retrieve records from the database.
6. posts = Post.objects.all()
7. Update: Modify existing records.
8. post = Post.objects.get(id=1)
9. post.title = "Updated Title"
10. post.save()
11. Delete: Remove records from the database.
12. post = Post.objects.get(id=1)
13. post.delete()
8. Middleware in Django

Q: What is Middleware in Django? Explain its role with an example.


A:
Middleware is a framework in Django for processing requests and responses globally.

Examples of Middleware Tasks:

 Security (e.g., SecurityMiddleware).


 Session handling (e.g., SessionMiddleware).
 GZip compression.

Example: Custom Middleware:

class CustomMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):


print("Before View")
response = self.get_response(request)
print("After View")
return response

9. Django Authentication and Authorization

Q: Explain Django’s authentication and authorization system.


A: Django provides built-in authentication and authorization systems for handling user login,
logout, permissions, and groups.

1. Authentication: Verifying a user's identity.


o Django uses authenticate() and login() functions to handle user login.
2. Authorization: Determining if a user has permission to perform certain actions.
o Permissions can be assigned to users or groups.

Features:

 User authentication (django.contrib.auth module).


 Permissions framework.
 Password hashing and security.
 Group-based permissions.

Example:
views.py:

from django.contrib.auth import authenticate, login, logout


from django.shortcuts import render, redirect
def login_view(request):
if request.method == "POST":
username = request.POST['username']
password = request.POST['password']
user = authenticate(request, username=username, password=password)
if user is not None:
login(request, user)
return redirect('home')
else:
return render(request, 'login.html', {'error': 'Invalid
credentials'})
return render(request, 'login.html')

def logout_view(request):
logout(request)
return redirect('login')

10. Registration Form in Django

Q: How do you create a user registration form in Django? Provide an example.


A: Django’s forms module can be used to create user registration forms.

Example:
forms.py:

from django import forms


from django.contrib.auth.models import User

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:

from django.shortcuts import render, redirect


from .forms import RegistrationForm

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})

11. Database Migrations in Django

Q: What are database migrations in Django? How are they performed?


A: Database migrations in Django help apply changes to the database schema based on the
models defined in the application.

Steps to Perform Migrations:

1. Create migration files:


2. python manage.py makemigrations
3. Apply migrations to the database:
4. python manage.py migrate
5. Check migration status:
6. python manage.py showmigrations

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.

12. Django Middleware

Q: Explain middleware in Django and how it is created.


A: Middleware in Django is a lightweight, low-level plugin system that processes requests and
responses globally.

How Middleware Works:

1. Middleware processes requests before they reach the view.


2. It processes responses after the view returns a response.

Example:
Custom middleware that adds a custom header:
middleware.py:
class AddHeaderMiddleware:
def __init__(self, get_response):
self.get_response = get_response

def __call__(self, request):


response = self.get_response(request)
response['X-Custom-Header'] = 'MyHeaderValue'
return response

Enable the middleware in settings.py:

MIDDLEWARE = [
...,
'myapp.middleware.AddHeaderMiddleware',
]

13. Cache in Django

Q: What is caching in Django? Explain its importance.


A: Caching is a technique to store frequently accessed data temporarily to reduce load time and
server overhead. Django provides robust caching support.

Types of Caches in Django:

1. In-memory caching (Memcached): Stores data in RAM.


2. File-based caching: Stores cache data in files.
3. Database caching: Uses the database to store cache data.
4. Custom caching: User-defined caching logic.

Example:
Using the low-level cache API:

from django.core.cache import cache

# Set a cache value


cache.set('key', 'value', timeout=60)

# Get the cache value


value = cache.get('key')

Benefits:

 Faster response times.


 Reduced database queries.
 Improved scalability.
14. Heroku Deployment

Q: Explain the steps for deploying a Django application on Heroku.


A:

1. Install Heroku CLI:


Download and install the Heroku Command Line Interface (CLI).
2. Prepare Django App:
o Install gunicorn for WSGI support.
o Create a Procfile specifying the web process:
o web: gunicorn myproject.wsgi
3. Install dj-database-url and whitenoise:
o Use dj-database-url to configure the database:
oimport dj_database_url
oDATABASES['default'] = dj_database_url.config()
oUse whitenoise for serving static files.
4. Configure settings.py:
5. STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
6. DEBUG = False
7. ALLOWED_HOSTS = ['your-heroku-app.herokuapp.com']
8. Deploy:
o Commit the changes to Git.
o Login to Heroku:
o heroku login
o Create a Heroku app:
o heroku create your-app-name
o Push code to Heroku:
o git push heroku main
9. Run Database Migrations:
10. heroku run python manage.py migrate
11. Access the App:
Visit https://your-app-name.herokuapp.com.

15. Git Repository Hosting Function

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:

1. Create a new repository on GitHub.


2. Initialize a Git repository locally:
3. git init
4. git add .
5. git commit -m "Initial commit"
6. Add the remote repository:
7. git remote add origin <repository-url>
8. Push the code to GitHub:
9. git push -u origin main

16. WSGI

Q: What is WSGI, and why is it used in web applications?


A: WSGI (Web Server Gateway Interface) is a Python standard for communication between web
servers and web applications.

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()

17. Decorators in Python

Q: What are decorators in Python? Explain with an example.


A: Decorators are functions that modify the behavior of another function or method.

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:

Function greet is being executed


Hello, Deepanshu

18. MVC and MVT in Django

Q: Differentiate between MVC and MVT.


A:

Aspect MVC (Model-View-Controller) MVT (Model-View-Template)


Controller Handles user input and updates the model/view. Managed by Django internally.
Template Not explicitly defined in MVC. Separate layer for the user interface.
Example Used in frameworks like Rails, Laravel. Used in Django.

MVT in Django:

1. Model: Handles database schema and queries.


2. View: Processes user requests and prepares data.
3. Template: Defines the UI for displaying data.

19. Django URLs and Views

Q: How do URLs and Views work in Django?


A: Django’s URL dispatcher maps URLs to views using urlpatterns in the urls.py file.

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')

When a user accesses /about/, the about view is executed.

20. Django Template and Template Inheritance

Q: Explain Django’s template system and template inheritance.


A:

Template System:

 Templates define the structure and layout of HTML pages.


 Use placeholders for dynamic content ({{ variable }}).

Template Inheritance:

 Allows reusing base templates for consistency.

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 %}

21. Django Middleware

Covered earlier.

22. Working with Static Files on Heroku

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

23. Handling WSGI with Gunicorn

Q: How do you use Gunicorn to handle WSGI in Django?


A:

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

3-a. Explain steps for creating a simple Flask App.

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.

3-b. Explain the Web Scraping process and Scrapy in detail.

1. Understand the Website:


o Analyze the website’s structure (HTML, elements, classes, etc.).
2. Set up Scrapy:
o Install using pip install scrapy.
3. Create a Scrapy Project:
o Run scrapy startproject <project_name> to create the project.
4. Write Spider:
o Define a spider in the spiders folder to crawl and parse data.
5. Send Requests:
o Use start_requests to send HTTP requests to web pages.
6. Parse Responses:
o Extract data using XPath or CSS selectors.
7. Store Data:
o Save extracted data to files (CSV, JSON, etc.) using Scrapy pipelines.

3-c. Explain Django with its unique features in detail.

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.

1. Client Sends Request:


o HTTP request sent to the server.
2. URL Routing:
o Django URL dispatcher maps the request to a view function.
3. View Logic:
o Executes business logic and interacts with the database.
4. Template Rendering:
o Prepares HTML response using templates.
5. Middleware:
o Processes the request/response before sending it back.
6. Response Sent:
o Sends the HTTP response back to the client.

3-e. Explain Django's Vulnerabilities or Security problems.

1. CSRF (Cross-Site Request Forgery):


o Use Django’s CSRF protection middleware.
2. SQL Injection:
o Prevented by ORM query parameterization.
3. XSS (Cross-Site Scripting):
o Django auto-escapes HTML in templates.
4. Clickjacking:
o Mitigate with the X-Frame-Options header.
5. Solution:
o Keep Django up-to-date and follow security practices.

3-f. Describe the role of frameworks in Python.

Frameworks:

 Simplify development by providing pre-built components.


 Examples:
o Django: Full-stack web framework.
o Flask: Lightweight web framework.
 Benefits:
o Code reusability, scalability, and faster development.
 Example:

from flask import Flask


app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World!"
app.run()

3-g. Explain working of Django Heroku with example.

1. Install Required Libraries:


o Install gunicorn, django-heroku, and whitenoise.
2. Settings Configuration:
o Add django_heroku.settings(locals()) in settings.py.
3. Procfile:
o Create a Procfile with web: gunicorn <project_name>.wsgi.
4. Push to GitHub:
o Deploy the project to a Git repository.
5. Deploy on Heroku:
o Use Heroku CLI commands to create and deploy the app.

Second Image

3-a. Explain Zappa and Flask in detail.

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.

3-b. Explain Webscraping with an example.

 Use BeautifulSoup to extract website data:

from bs4 import BeautifulSoup


import requests

url = 'http://example.com'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
print(soup.title.text)

3-c. Discuss Django MVC architecture in detail with a diagram.

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.

3-d. Why is Django called a loosely coupled framework?

1. Components Independence:
o Each component (Model, View, Template) operates independently.
2. Flexibility:
o Easily replaceable or customizable components.

3-e. Write the steps to add an email field in Django form.

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.

3-g. List some popular applications using Heroku.

1. Slack Bots.
2. E-commerce Platforms.
3. Data Dashboards.
Here are detailed answers to the questions:

4-a. Explain Tkinter-GUI applications in detail with example. (CO1)

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 the main window


root = tk.Tk()
root.title("Simple Tkinter App")

# Create a label
label = tk.Label(root, text="Hello, Tkinter!")
label.pack()

# Create a button
def on_button_click():
label.config(text="Button Clicked!")

button = tk.Button(root, text="Click Me", command=on_button_click)


button.pack()

# Run the application


root.mainloop()

Explanation:

 Tk() initializes the main application window.


 Widgets like Label and Button are used to display text and interact with the user.
 The command parameter binds the button to the on_button_click function.

4-b. Write short notes on:

a) ChainMap:
 Part of the collections module.
 Combines multiple dictionaries into a single view.
 Changes in the original dictionaries reflect in the ChainMap.

Example:

from collections import ChainMap


dict1 = {'a': 1, 'b': 2}
dict2 = {'c': 3, 'd': 4}
chain = ChainMap(dict1, dict2)
print(chain['a']) # Output: 1

b) Counter:

 Used for counting hashable objects.


 Part of the collections module.

Example:

from collections import Counter


data = ['a', 'b', 'a', 'c', 'b', 'b']
count = Counter(data)
print(count) # Output: Counter({'b': 3, 'a': 2, 'c': 1})

c) Deque:

 Double-ended queue.
 Supports O(1) operations for appending and popping elements from both ends.

Example:

from collections import deque


dq = deque([1, 2, 3])
dq.appendleft(0) # Add to the front
dq.append(4) # Add to the rear
print(dq) # Output: deque([0, 1, 2, 3, 4])

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.

5-b. What is Django? Define its convenient features in detail. (CO2)

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:

 Verifies the identity of a user (e.g., username and password).


 Django provides a built-in authentication system.

Authorization:

 Determines permissions and access levels for authenticated users.


 Managed via permissions and groups in Django.

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:

from django.contrib.auth.models import User


from django.contrib.auth.decorators import login_required, permission_required

@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:

 Use the render function to send context data.

Example:

from django.shortcuts import render

def home(request):
context = {'name': 'Deepanshu', 'age': 25}
return render(request, 'home.html', context)

Template (home.html):

<p>Name: {{ name }}</p>


<p>Age: {{ age }}</p>

Output:

Name: Deepanshu
Age: 25

8-a. Steps to Create a Functional Website in Django (CO5)

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

Here are detailed answers to the questions for each section:

4. Answer any one of the following:

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:

from quixote.publish import Publisher

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:

1. Parsing: Supports multiple parsers like HTML, XML, and lxml.


2. Search and Navigation: Allows searching elements using tags, attributes, and CSS selectors.
3. Modification: You can modify the HTML content dynamically.
4. Encoding: Handles encoding issues and extracts data even from broken markup.

Example:

from bs4 import BeautifulSoup

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>
"""

soup = BeautifulSoup(html, 'html.parser')


title = soup.title.string
intro = soup.find('p', {'class': 'intro'}).text

print(f"Title: {title}")
print(f"Introduction: {intro}")

Output:

Title: Sample Website


Introduction: This is a tutorial for web scraping.

5. Answer any one of the following:

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:

Feature Django Flask

Framework Type Full-stack Microframework

Built-in Features Yes (e.g., ORM, admin panel) No (requires plugins)

Flexibility Less flexible due to conventions Highly flexible

Learning Curve Steeper Easier

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:

1. Create a Django App:


2. django-admin startapp student_app

3. Define the Model:


In models.py:
4. from django.db import models
5.
6. class Student(models.Model):
7. roll_no = models.IntegerField()
8. name = models.CharField(max_length=100)
9. student_class = models.CharField(max_length=50)
10. department = models.CharField(max_length=100)
11.
12. def __str__(self):
13. return self.name

14. Add App to Settings:


Add student_app to INSTALLED_APPS in settings.py.
15. Apply Migrations:
16. python manage.py makemigrations
17. python manage.py migrate
18. Use Model in Admin Panel:
Register the model in admin.py:
19. from .models import Student
20.
21. admin.site.register(Student)

6. Answer any one of the following:

6-a. Create a registration form using Django and add email configuration settings.
(CO3)

Answer:
Steps:

1. Create a form in forms.py:


2. from django import forms
3.
4. class RegistrationForm(forms.Form):
5. username = forms.CharField(max_length=50)
6. email = forms.EmailField()
7. password = forms.CharField(widget=forms.PasswordInput)

8. Create a view in views.py:


9. from django.shortcuts import render
10. from .forms import RegistrationForm
11.
12. def register(request):
13. if request.method == 'POST':
14. form = RegistrationForm(request.POST)
15. if form.is_valid():
16. # Save user data here
17. print("Form is valid")
18. else:
19. form = RegistrationForm()
20. return render(request, 'register.html', {'form': form})

21. Add email settings in settings.py:


22. EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
23. EMAIL_HOST = 'smtp.gmail.com'
24. EMAIL_PORT = 587
25. EMAIL_USE_TLS = True
26. EMAIL_HOST_USER = 'your_email@gmail.com'
27. EMAIL_HOST_PASSWORD = 'your_password'

28. Create register.html template:


29. <form method="post">
30. {% csrf_token %}
31. {{ form.as_p }}
32. <button type="submit">Register</button>
33. </form>
6-b. Describe security issues in Django and explain the ways of dealing with it.
(CO3)

Answer:

1. SQL Injection:
o Issue: Exploits user input to execute malicious SQL queries.
o Solution: Use Django ORM to handle database queries.

2. Cross-Site Scripting (XSS):


o Issue: Malicious scripts injected into web pages viewed by users.
o Solution: Use Django’s auto-escaping templates.

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. Answer any one of the following:

7-a. Explain request-response life cycle of Django with diagram and code. (CO4)

Answer:

1. Request Initiation: The user sends a request to the server.


2. URL Routing: Django matches the URL to a view.
3. View Processing: The view fetches/processes data and sends it to templates.
4. Response Rendering: The response is rendered into HTML and sent back.

Diagram:

[User Request] → [URL Dispatcher] → [View] → [Template] → [Response]

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.

Steps for Database Migration:

1. Create a Model: Define your models in models.py.


2. Generate Migrations:
3. python manage.py makemigrations

This creates a migration file reflecting changes made to the models.

4. Apply Migrations:
5. python manage.py migrate

This applies the migration to the database.

Fetching Data from the Database:


Once models are migrated, data can be fetched using Django's ORM.

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)

# Fetching data in a view


from .models import Student

def student_list(request):
students = Student.objects.all() # Fetch all records
return render(request, 'students.html', {'students': students})

8. Answer any one of the following:


8-a. Heroku and AWS serve similar goals but should be used in different use cases.
Justify. (CO5)

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.

Example Use Case: Enterprises deploying highly scalable and customizable


architectures.

Justification: Use Heroku for ease of deployment and AWS for advanced configurations and
scalability.

8-b. Explain handling of WSGI with Gunicorn in detail. (CO5)

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.

How Gunicorn Handles WSGI:

1. Worker Processes: Gunicorn spawns multiple worker processes to handle requests


concurrently.
2. Request Handling: It listens for HTTP requests and forwards them to the WSGI-compatible
application.
3. Response Sending: The application processes the request and sends the response back to
Gunicorn, which relays it to the client.

Steps to Use Gunicorn with Django:

1. Install Gunicorn:
2. pip install gunicorn

3. Run Gunicorn Server:


4. gunicorn myproject.wsgi:application --bind 0.0.0.0:8000

5. Deployment: Use Gunicorn behind a reverse proxy like Nginx for production.

Advantages of Gunicorn:

 Efficient request handling with multiple workers.


 Compatible with many web frameworks.

Example Gunicorn Command:

gunicorn --workers=3 --bind 0.0.0.0:8000 myproject.wsgi:application

You might also like