FSD Solved MQP
FSD Solved MQP
ANSWERS
VTUCSE21
Module-01
Q.01
a. Define: (4 Marks)
Marks) Ans:
Web frameworks are software tools designed to support the development of web
applications, including web services, web resources, and web APIs.
Examples include Django for Python, Ruby on Rails for Ruby, and Laravel for PHP.
URLs:
URLs (Uniform Resource Locators) are the addresses used to access resources on the
internet.
A URL consists of the protocol (e.g., http), domain name (e.g., www.example.com), and
the path to the resource (e.g., /path/to/resource).
1. Admin Interface:
3. MTV Architecture:
4. Security:
Includes built-in protections against common attacks like SQL injection, XSS, and CSRF.
Regular security updates and best practices.
Example: CSRF tokens are automatically included in forms.
5. Scalability:
2
1c. Explain MVC Architecture: (8 Marks)
1. Model:
Represents the data and business logic.
Manages data storage and retrieval.
Example: In a blogging application, the Post model represents blog posts.
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
2. View:
Displays the data (user interface).
Presents data to the user and handles user interaction.
Example: The template that displays the list of blog posts.
def show_posts(request):
posts = Post.objects.all()
return render(request, 'posts.html', {'posts': posts})
3. Controller:
Handles user input and updates the Model and View accordingly.
Acts as an intermediary between Model and View.
Example: A function that processes form submissions and updates the blog post
data.
def add_post(request):
if request.method ==
'POST': title =
request.POST['title']
content = request.POST['content']
Post.objects.create(title=title, content=content)
return redirect('show_posts')
3
Q.02
a. Define: (4 Marks)
b. List out Django Exceptions & Errors with neat diagram. (8 Marks)
c. Develop a Django app that displays current date & time. (8 Marks)
Loose Coupling:
4
2b. List out Django Exceptions & Errors with neat diagram: (8
1. ObjectDoesNotExist:
Raised when an object is not found in the database.
Example: MyModel.objects.get(pk=1) raises ObjectDoesNotExist if no record
with primary key 1 exists.
2. MultipleObjectsReturned:
Raised when a query returns multiple objects but only one was expected.
Example: MyModel.objects.get(name='example') raises MultipleObjectsReturned
if more than one record with the name 'example' exists.
3. FieldError:
Raised for problems with model fields.
Example:Using a non-existent field in a query:
MyModel.objects.filter(nonexistent_field='value').
4. ValidationError:
Raised when data validation fails.
Example: MyForm({'name': ''}) raises ValidationError if the name field is
required but not provided.
5. PermissionDenied:
Raised when a user does not have the necessary permissions to access a resource.
Example: Manually raised in a view: from django.core.exceptions import
PermissionDenied.
5
Fig: Django Request-Response Cycle
6
2c. Develop a Django app that displays current date & time: (8
INSTALLED_APPS = [
# ...
'date_app',
import timezone
def current_datetime(request):
now = timezone.now()
7
5. Configure URL in myapp/urls.py:
current_datetime urlpatterns = [
include urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
8
Module 2
Q.03
Model-View-Template (MVT)
Architecture:
Model:
View:
9
def book_list(request):
books = Book.objects.all()
Template:
10
3b. Explain Template Inheritance with an example (10
Example: base.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
home.html:
{% extends "base.html" %}
{% block content %}
<h1>Welcome to my site</h1>
{% endblock %}
11
In this example:
base.html is the base template that defines the common structure of the HTML document.
home.html extends base.html and overrides the title and content blocks to
provide specific content for the home page.
1. Reusability:
Base Template (base.html): Contains the common layout and structure.
Child Templates: Extend the base template and override specific blocks
to customize content.
2. Maintaining Consistency:
Changes to the base template automatically reflect across all child
templates, ensuring a consistent layout.
3. Avoiding Duplication:
Common elements (like headers, footers) are defined once in the base
template, avoiding redundancy.
Benefits:
Easy Updates: Modify the base template to update the layout across all pages.
Clean Code: Keeps template files clean and manageable by separating common
structure from page-specific content.
Flexibility: Allows specific sections of the layout to be customized as needed.
12
Q.04
b. Develop a simple Django app that displays an unordered list of fruits and ordered list
of selected students for an event. (10 Marks)
Example:
# views.py
def greet(request):
13
Python Templates:
Python templates like Jinja2 can also be used for rendering HTML.
Jinja2 is similar to Django's templating engine but offers more control and flexibility.
Example:
<!-- template.html (Jinja2) -->
<h1>Hello, {{ name }}!</h1>
# example.py
from jinja2 import Template
template = Template('<h1>Hello, {{ name
}}!</h1>') print(template.render(name='John'))
The Jinja2 template is defined within the Python code with {{ name }} as a placeholder.
A Template object is created with the HTML string.
The render method is called with the context (name='John'), generating and printing
the final HTML.
Differences:
14
4b. Develop a simple Django app that displays an unordered list of fruits and ordered list
of selected students for an event (10 Marks)
def display_lists(request):
fruits = ["Apple", "Banana", "Cherry"]
students = ["Alice", "Bob", "Charlie"]
return render(request, 'lists.html', {'fruits': fruits, 'students': students})
urlpatterns = [
path('lists/', display_lists, name='display_lists'),
]
15
6. Include App URLs in myproject/urls.py:
from django.contrib import admin
from django.urls import path,
include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
<h1>Selected Students</h1>
<ol>
{% for student in students %}
<li>{{ student }}</li>
{% endfor %}
</ol>
</body>
16
</html>
17
8. Run the Server:
python manage.py runserver
9. Access the URL:
Navigate to http://localhost:8000/lists/ to see the unordered list of fruits
and ordered list of selected students.
18
Module 3
Q.05
Marks) Migration:
Migration is the process of moving the database schema and data from one version
to another.
In Django, migrations are used to propagate changes you make to your models (adding
a field, deleting a model, etc.) into your database schema.
This ensures that the database schema remains in sync with your model definitions.
Example:
1. Create a New
Model: # models.py
from django.db import models
class Author(models.Model):
name = models.CharField(max_length=100)
birth_date = models.DateField()
2. Generate Migrations
python manage.py makemigrations
19
3. Apply Migrations:
python manage.py migrate
This command applies the migrations to the database, creating the
necessary tables and columns.
4. Example Output:
Migrations for 'myapp':
myapp/migrations/0001_initial.py
- Create model Author
5. Check Database
The Author table should now exist in the database with the specified columns.
5b. Create a simple Django project called urls_dispatcher_example with two applications
(articles and blog) (10 Marks)
Step-by-Step Guide:
20
4. Project Structure:
urls_dispatcher_example/
├── articles/
│ ├── init .py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations/
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── blog/
│ ├── init .py
│ ├── admin.py
│ ├── apps.py
│ ├── migrations/
│ ├── models.py
│ ├── tests.py
│ └── views.py
├── manage.py
└── urls_dispatcher_example/
├── init .py
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py
21
5. Define Views for Each App:
articles/views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Welcome to the Articles section")
blog/views.py:
from django.http import HttpResponse
def index(request):
return HttpResponse("Welcome to the Blog section")
urlpatterns = [
path('', views.index, name='index'),
]
blog/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.index, name='index'),
]
22
7. Include App URLs in the Project's urls.py:
urls_dispatcher_example/urls.py:
from django.contrib import admin
from django.urls import path,
include
urlpatterns = [
path('admin/', admin.site.urls),
path('articles/', include('articles.urls')),
path('blog/', include('blog.urls')),
]
23
Q.06
urlpatterns = [
path('', views.index, name='index'),
]
urlpatterns = [
path('', views.index, name='index'),
path('about/', views.about,
name='about'),
]
24
Step 3: Include the App's urls.py in the Project's urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
]
25
6b. Discuss Django Form Submission (10
def contact(request):
form = ContactForm()
return render(request, 'contact.html', {'form': form})
26
3. Handling Form Submission:
Process the form data when the form is submitted.
# views.py
from django.shortcuts import render
from .forms import ContactForm
def contact(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# Perform desired operations (e.g., save data, send email)
else:
form = ContactForm()
return render(request, 'contact.html', {'form': form})
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
27
Module 4
Q.07
Q.08
a. Discuss how to create templates for each view with an example. (10 Marks)
Generic Views:
Generic Views in Django are pre-built views that simplify common tasks like
displaying a list of objects or handling forms.
They provide a way to handle these tasks with less code by leveraging Django's built-
in functionality.
These views are designed to handle common patterns of web application
functionality and can be easily customized for specific needs.
1. ListView:
Displays a list of objects from a model.
Example
from django.views.generic import
ListView from .models import Book
class BookListView(ListView):
model = Book
template_name = 'book_list.html'
28
2. DetailView:
Displays detailed information about a single object.
Example
from django.views.generic import
DetailView from .models import Book
class BookDetailView(DetailView):
model = Book
template_name = 'book_detail.html'
3. CreateView:
Provides a form to create a new object.
Example
from django.views.generic.edit import CreateView
from .models import Book
class BookCreateView(CreateView):
model = Book
fields = ['title', 'author', 'published_date']
template_name = 'book_form.html'
4. UpdateView:
Provides a form to update an existing object.
Example
from django.views.generic.edit import
UpdateView from .models import Book
class BookUpdateView(UpdateView):
model = Book
fields = ['title', 'author',
'published_date'] template_name =
29
'book_form.html'
30
5. DeleteView:
Provides a form to confirm the deletion of an object.
Example
from django.views.generic.edit import DeleteView
from .models import Book
class BookDeleteView(DeleteView):
model = Book
success_url = '/books/'
template_name = 'book_confirm_delete.html'
Extensions):
MIME is a standard for specifying the type of data being sent over the internet.
It extends the format of email messages to support text in character sets other than
ASCII, attachments, and multimedia content.
MIME types (also known as media types) are used to specify the nature and format of
a document, file, or set of bytes.
1. text/html:
Represents HTML documents.
Example: A web page.
Usage: Content-Type: text/html
2. text/plain:
Represents plain text without formatting.
Example: A text file.
31
Usage: Content-Type: text/plain
32
3. image/jpeg:
Represents JPEG image files.
Example: A photograph.
Usage: Content-Type: image/jpeg
4. image/png:
Represents PNG image files.
Example: A logo or graphic.
Usage: Content-Type: image/png
5. application/json:
Represents JSON data.
Example: JSON data for API responses.
Usage: Content-Type: application/json
6. application/xml:
Represents XML data.
Example: XML data used in APIs or configurations.
Usage: Content-Type: application/xml
7. application/pdf:
Represents PDF documents.
Example: A document or report.
Usage: Content-Type: application/pdf
8. multipart/form-data:
Represents form data that includes files.
Example: File uploads in web forms.
Usage: Content-Type: multipart/form-data
33
8a. Discuss how to create templates for each view with an example (10
1. Define a View:
Create a view function or class-based view to handle the request and render
a template.
# views.py
from django.shortcuts import render
def home_view(request):
return render(request, 'home.html')
home.html:
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
34
<h1>Welcome to the Home Page</h1>
</body>
</html>
urlpatterns = [
path('', home_view, name='home'),
]
35
8b. Explain Dynamic CSV using database (10
Dynamic CSV involves generating CSV files from database queries using Django.
This is useful for exporting data in a format that can be easily used in spreadsheets
or other applications.
Example:
1. Define a
Model: #
models.py
from django.db import models
class MyModel(models.Model):
field1 =
models.CharField(max_length=100) field2
= models.IntegerField()
def export_csv(request):
# Create the HTTP response with CSV content
type response =
HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="data.csv"'
36
# Create a CSV writer
writer =
csv.writer(response)
37
# Write the header row
writer.writerow(['Field1', 'Field2'])
return response
urlpatterns = [
path('export-csv/', export_csv, name='export_csv'),
]
38
Module 5
Q.09
b. Develop a registration page for student enrollment without page refresh using AJAX.
(10 Marks)
Q.10
b. Develop a search application in Django using AJAX that displays courses enrolled by
a student being searched. (10 Marks)
1. HTTP Request:
A request sent from the client (usually a web browser) to the server to retrieve
or send data.
Components:
1. Method: Determines the action (GET, POST, etc.).
2. URL: Specifies the resource.
3. Headers: Includes metadata (e.g., Accept, Content-Type).
4. Body: Data sent with the request (e.g., form data for POST requests).
39
Example:
GET /page.html HTTP/1.1
Host: www.example.com
Accept: application/xhtml+xml
2. HTTP Response:
The server's reply to the client's request, containing the requested resource or
an error message.
Components:
1. Status Code: Indicates the result (e.g., 200 OK, 404 Not Found).
2. Headers: Metadata about the response (e.g., Content-Type).
3. Body: The content (e.g., XHTML document).
Example:
HTTP/1.1 200 OK
Content-Type: application/xhtml+xml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Example Page</title></head>
<body><h1>Hello, world!</h1></body>
</html>
40
9b. Develop a registration page for student enrollment without page refresh using AJAX (10
Marks)
fetch('/register/', {
method: 'POST',
headers: {
'X-CSRFToken': '{{ csrf_token }}', // CSRF
protection 'Content-Type': 'application/x-www-form-
urlencoded'
},
body: new URLSearchParams(new FormData(this)).toString()
})
.then(response => response.text())
.then(data => {
document.getElementById('response').innerHTML = data; // Display
response
})
.catch(error => console.error('Error:', error));
});
41
});
42
</script>
</head>
<body>
<form id="registration-form">
<input type="text" name="name" placeholder="Name" required>
<input type="email" name="email" placeholder="Email" required>
<button type="submit">Register</button>
</form>
<div id="response"></div>
</body>
</html>
43
The form submission uses JavaScript's fetch API to send data to the server without
refreshing the page.
CSRF protection is included by sending the CSRF token.
Q.10
b. Develop a search application in Django using AJAX that displays courses enrolled by
a student being searched. (10 Marks)
44
settings.py:
STATIC_URL = '/static/'
{% load static %}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
</body>
</html>
Django's static files management allows including JavaScript files via the {% static %}
tag.
Use defer attribute for better performance, as it loads the script after the HTML content.
45
10b. Develop a search application in Django using AJAX that displays courses enrolled by a
student being searched (10 Marks)
46
2. Django View (views.py):
from django.http import JsonResponse
from .models import Student
def search(request):
query = request.GET.get('q', '')
courses = []
if query:
student = Student.objects.filter(name icontains=query).first()
if student:
courses = list(student.courses.values_list('name', flat=True))
return JsonResponse({'courses': courses})
urlpatterns = [
path('search/', search, name='search'),
]
The search feature uses AJAX to fetch and display data without a page refresh.
The server responds with JSON data, which is processed by JavaScript to update the
page content dynamically.
47