21CS62 Fullstack Development 2
21CS62 Fullstack Development 2
Solution
1. a) What is a web framework? Explain the django-admin command with an example.
Web Framework: A web framework is a software framework that provides a standard way to
build and deploy web applications. Frameworks simplify the development process by
offering pre-built modules, libraries, and tools that allow developers to create web
applications without reinventing the wheel. Web frameworks often provide solutions for
routing (handling different web addresses), database management, templating (rendering
HTML with dynamic data), session management, and other common functionalities.
Examples of popular web frameworks include Django (Python), Ruby on Rails (Ruby), Laravel
(PHP), and Spring (Java).
Example: To create a new Django project, you can use the command:
History of Django: Django was created in 2003 by Adrian Holovaty and Simon Willison while
working at the Lawrence Journal-World, a newspaper company in Kansas, USA. They needed
a web development tool to meet the tight deadlines and handle high-demand web
applications for the newspaper. Recognizing the potential of their tool, they open-sourced
Django in 2005 to allow other developers to use and improve it. Named after jazz guitarist
Django Reinhardt, the framework was designed to support "rapid development" and focus
on the "DRY" (Don't Repeat Yourself) principle. Django has since become one of the most
widely used web frameworks for building robust, secure, and scalable web applications.
def hello_world(request):
In this example, hello_world is a simple view function that takes a request and returns a response
saying "Hello, world!" The HttpResponse object is used to send the text back to the client.
OR
Solution
Django Request Processing: Django processes an incoming web request in several steps:
1. URL Routing: Django first checks the URL of the request against a list of URL patterns
defined in the urls.py file. It matches the incoming URL with one of these patterns.
2. View Function: Once a URL is matched, Django calls the corresponding view function
for that pattern.
4. Response: After processing the request, the view returns a response, typically
rendered HTML or JSON data. The response goes back through the middleware and
is finally sent to the client.
2. b) Identify the key philosophy behind URL confs and loose coupling.
URL Confs and Loose Coupling: In Django, URLs are defined in a separate urls.py file and
mapped to view functions. This separation, known as "loose coupling," ensures that the
application's components are independent. URL configurations (URLConfs) can be changed
without affecting view logic. This design makes Django applications more modular and
maintainable since URLs and view logic are loosely coupled.
Mapping URLs to Views: In Django, URL patterns are defined in urls.py, which maps each
URL pattern to a specific view function. When a URL is accessed, Django looks for a matching
pattern in urls.py and calls the corresponding view function.
urlpatterns = [
Here, the URL pattern hello/ is mapped to the hello_world view function in views.py. When /hello/ is
accessed, Django invokes hello_world and returns its response.
Module-2
Solution
3. a) What is a template? Explain the basics of template systems with an example.
Template: In Django, templates are text files that define the structure of a web page.
Templates use variables and logic (e.g., loops, conditionals) to render dynamic data. Django’s
template system separates presentation from business logic, making the code cleaner and
easier to maintain.
Here, {{ user.name }} is a variable that gets replaced with the actual data when the template is
rendered.
Example:
<html>
<body>
<h1>Website Header</h1>
</body>
</html>
html
Copy code
{% extends "base.html" %}
{% block content %}
{% endblock %}
OR
4. a. Identify the different types of tags and filters in Django template system.
b. Explain the models in Django with an example.
(12 Marks, 08 Marks)
Solution
4. a) Identify the different types of tags and filters in the Django template system.
o Tags control logic, like {% for %}, {% if %}, and {% block %}.
Django Models: Models represent the structure of the database in Django. They are Python
classes that inherit from models.Model and map to database tables.
Example:
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
age = models.IntegerField()
Module-3
5. a. How to activate and configure the admin interface in Django for managing application
data?
b. Explain the process of handling and processing forms in a web application using Django.
(08 Marks, 12 Marks)
Solution
5. a) How to activate and configure the admin interface in Django for managing application data?
Custom Admin Views: In Django, the admin interface provides a default way to manage
models, but you can customize how your models are displayed in the admin by creating an
Admin class for each model and registering it with admin.site.register. Customization can
include displaying specific fields, adding search functionality, filtering, and defining custom
actions.
Example:
class StudentAdmin(admin.ModelAdmin):
search_fields = ('name',)
list_filter = ('age',)
admin.site.register(Student, StudentAdmin)
Here, StudentAdmin customizes the admin interface for the Student model, showing only the name
and age fields, adding search functionality for name, and a filter for age.
Solution
To create a feedback form in Django, we’ll follow a few steps. A feedback form generally collects data
such as user name, email, feedback text, and rating. In Django, forms can be created using Django's
form library by defining a form class.
Step-by-Step Program
cd feedback_project
2. Define the Model for Feedback In the models.py file of feedback_app, define a Feedback
model to store the feedback information in the database.
# feedback_app/models.py
class Feedback(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
feedback = models.TextField()
rating = models.IntegerField(choices=[(1, 'Poor'), (2, 'Fair'), (3, 'Good'), (4, 'Very Good'), (5,
'Excellent')])
def __str__(self):
o rating is an integer field that stores feedback ratings, with predefined choices from 1
to 5.
3. Create a Form for Feedback In forms.py file in feedback_app, define a Django form based on
the Feedback model.
# feedback_app/forms.py
class FeedbackForm(forms.ModelForm):
class Meta:
model = Feedback
4. Create a View to Handle Feedback Submission In views.py, define a view function to render
the feedback form and handle form submissions.
# feedback_app/views.py
def feedback_view(request):
if request.method == 'POST':
form = FeedbackForm(request.POST)
if form.is_valid():
return redirect('feedback_success')
else:
form = FeedbackForm()
o If the request method is POST, it means the form has been submitted, so we check if
the form data is valid. If valid, we save the data to the database.
<h2>Feedback Form</h2>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
</form>
o {% csrf_token %} is a Django template tag that adds a CSRF token for security.
6. Define URL Patterns In urls.py, configure URLs to link to the feedback form view.
# feedback_app/urls.py
urlpatterns = [
7. Add Feedback URL to Project’s URL Configuration Link the app’s URLs to the main project
URL configuration.
# feedback_project/urls.py
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('feedback_app.urls')),
1. Model Management
Admin users can view, add, edit, and delete data records directly from the interface. For
example, an administrator can manage all entries in the Feedback model.
2. Customizable Interface
Django allows you to customize how models appear in the admin interface using the
ModelAdmin class in admin.py. You can specify how fields are displayed, apply filters, and
define search functionality for improved data management.
# feedback_app/admin.py
class FeedbackAdmin(admin.ModelAdmin):
admin.site.register(Feedback, FeedbackAdmin)
o list_display shows the specified fields on the list view in the admin.
6(c) How to Create Forms in Django? What Does This Class Do in Python Interpreter?
Creating Forms in Django
In Django, forms are created using the forms module in two primary ways:
# feedback_app/forms.py
class SimpleFeedbackForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
feedback = forms.CharField(widget=forms.Textarea)
rating = forms.ChoiceField(choices=[(1, 'Poor'), (2, 'Fair'), (3, 'Good'), (4, 'Very Good'), (5,
'Excellent')])
2. Model Forms
Django’s ModelForm class is used to create forms that are directly tied to a model. This
automatically generates form fields based on model fields, making it easier to create forms
for database records.
# feedback_app/forms.py
class FeedbackForm(forms.ModelForm):
class Meta:
model = Feedback
In Python, a class is a blueprint for creating objects. When you create a form class in Django, Python's
interpreter processes the class definition and creates a new type. For example, when defining
FeedbackForm, Python:
When you instantiate this form class (e.g., form = FeedbackForm()), Python creates an object of this
class type, allowing you to interact with it (e.g., display form fields, validate data). In a Django
context, the form class thus encapsulates all functionality needed for form data handling, validation,
and rendering.
Module-4
SOLUTION
In Django, Generic Views are a type of view provided by Django’s class-based views system that
streamline the process of creating common views for performing tasks like displaying a list of items,
retrieving details of a specific item, creating, updating, or deleting objects. These views are called
"generic" because they are designed to handle common patterns, reducing the amount of code
developers need to write and making Django applications easier to develop and maintain.
1. Reduces Code Duplication: Generic views eliminate the need to write boilerplate code for
repetitive tasks.
3. Efficiency: They streamline development by providing built-in views for common actions like
displaying a list of objects or a detailed view of an object.
# views.py
class PostListView(ListView):
model = Post
# views.py
class PostDetailView(DetailView):
model = Post
template_name = 'blog/post_detail.html'
context_object_name = 'post'
# views.py
class PostCreateView(CreateView):
model = Post
form_class = PostForm
template_name = 'blog/post_form.html'
# views.py
class PostUpdateView(UpdateView):
model = Post
form_class = PostForm
template_name = 'blog/post_form.html'
success_url = '/posts/'
# views.py
class PostDeleteView(DeleteView):
model = Post
template_name = 'blog/post_confirm_delete.html'
success_url = '/posts/'
Generic views are implemented as classes that inherit from Django's View base class or
TemplateView class. Each generic view provides specific methods for handling HTTP requests, such as
get, post, and put. The generic views automatically map these methods to perform actions like
retrieving, creating, updating, or deleting database records.
For example:
ListView internally calls get_queryset() to retrieve a list of objects from the database.
CreateView and UpdateView automatically handle form validation and saving the data to
the database.
Using generic views can significantly reduce development time, especially for common tasks. By
simply subclassing these views and providing minimal configuration (like specifying the model,
template, and sometimes form class), developers can create powerful views with minimal code.
Cookies are small pieces of data stored on the client’s browser that can be used by web servers to
track and remember information about the user’s session or preferences. In Django, cookies are
primarily used to store small bits of information on the client side, allowing the server to
"remember" users across requests.
2. Retrieving a Cookie: On subsequent requests, the browser sends the stored cookies back to
the server, allowing the server to retrieve stored information and personalize the user
experience.
3. Expiration: Cookies can have expiration dates, after which they are automatically deleted.
They can also be session-based, meaning they are deleted when the browser is closed.
Django provides a straightforward way to work with cookies through the HttpResponse object.
1. Setting a Cookie
Here’s an example of setting a cookie in a Django view:
# views.py
def set_cookie_view(request):
return response
2. Retrieving a Cookie
Once a cookie has been set, it can be accessed in subsequent requests:
# views.py
def get_cookie_view(request):
username = request.COOKIES.get('username')
if username:
else:
3. Deleting a Cookie
To delete a cookie, set its expiry date to a past time or use the delete_cookie() method.
# views.py
def delete_cookie_view(request):
response.delete_cookie('username')
return response
A common example is tracking the number of visits a user has made to the site. Here’s how you
could implement this in Django:
# views.py
def visit_count_view(request):
return response
visit_count + 1 increments the visit count each time the user accesses this view.
set_cookie('visit_count', visit_count, max_age=86400) updates the cookie with the new visit
count and sets it to expire in 24 hours (86400 seconds).
Each time the user visits, they’ll see an updated count. This information can be useful for customizing
the user experience, like showing a welcome message based on the number of visits.
1. Security: Cookies are stored on the client’s device and can be accessed or tampered with by
the user. For sensitive data, avoid storing it directly in cookies or use a secure cookie setting
(HttpOnly and Secure flags).
2. Size Limitations: Cookies have a size limit of about 4 KB, so they should be used only for
small pieces of data.
3. Session Cookies: Django also has a session framework that uses cookies to store session IDs
while storing the session data on the server. This is a secure way to manage user sessions as
only the session ID is stored on the client side.
SOLUTION
In Django, user authentication is the process of verifying the identity of a user who is attempting to
access a system. Django provides a built-in authentication system that manages user accounts,
passwords, permissions, and groups. It handles user login, logout, and registration in a secure
manner.
The Django authentication system mainly revolves around the following components:
1. User Model
o Django comes with a built-in User model (located in django.contrib.auth.models)
which includes fields like username, password, email, first_name, and last_name.
o The User model supports creating, updating, and deleting users, as well as setting
permissions and managing groups.
o Developers can either use Django's built-in User model or create a custom user
model if they need additional fields or custom behavior.
2. Password Management
o Django stores passwords securely by hashing them before storing them in the
database, ensuring that plaintext passwords are never saved.
o The set_password and check_password methods in Django's User model are used to
hash passwords and verify them during login.
login(): After authentication, this function is used to log the user into the
session, allowing them to access protected resources.
logout(): This function logs the user out of the current session, ending their
authenticated session.
LogoutView: Logs the user out and redirects them to a specified page.
o This middleware retrieves the currently logged-in user from the session and assigns
it to request.user in each view, so the application can know if a user is authenticated
or not.
o Permissions allow specific actions like "add," "change," and "delete" on certain
models.
o User Login:
3. If credentials are valid, the login() function logs the user in, creating a session for them.
4. The user can then access protected resources since request.user is now set to the
authenticated user.
o User Logout:
1. When a user clicks "logout," the logout() function ends the session.
# views.py
def user_login(request):
if request.method == 'POST':
username = request.POST['username']
password = request.POST['password']
login(request, user)
return redirect('home')
else:
def user_logout(request):
logout(request)
return redirect('login')
In this code:
A sitemap is an XML file that lists the URLs of a website along with additional metadata (e.g., when a
URL was last updated, how frequently it changes, and its importance). Search engines like Google
and Bing use sitemaps to index websites more effectively, improving the site’s search engine
optimization (SEO).
Django’s sitemap framework (django.contrib.sitemaps) simplifies the process of creating and
managing sitemaps for websites. It provides a way to automatically generate XML sitemaps that can
be submitted to search engines.
1. Improved SEO: Sitemaps help search engines discover and index all pages on a website,
especially those that might not be accessible via navigation.
2. Enhanced Crawling: Search engines can use metadata in the sitemap (e.g., update frequency
and priority) to optimize the crawl rate.
3. Better Visibility for Dynamic Sites: Websites that frequently update content, like blogs or
news sites, benefit from sitemaps, ensuring new content is indexed faster.
The Django sitemap framework provides tools to create sitemaps easily. Here’s how it works:
o The first step is to create a sitemap class for each set of URLs you want to include.
# sitemaps.py
class BlogPostSitemap(Sitemap):
changefreq = "weekly"
priority = 0.8
def items(self):
return BlogPost.objects.all()
return obj.updated_at
o priority: Specifies the importance of the page, relative to other pages on the site.
o items(): Returns a queryset of objects to include in the sitemap (e.g., all blog posts).
o After defining the sitemap classes, the next step is to configure them in Django’s URL
configuration.
# urls.py
sitemaps = {
'blog': BlogPostSitemap,
urlpatterns = [
o The sitemap view automatically generates an XML sitemap based on the specified
sitemap classes.
o You can create multiple sitemap classes for different models or types of content on
your website.
o You can add additional fields like priority to indicate the relative importance of
pages.
o After creating the sitemap, you can submit it to search engines like Google Search
Console and Bing Webmaster Tools.
o This helps ensure that search engines crawl your website efficiently and keep their
index up-to-date.
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url>
<loc>https://example.com/blog/post1</loc>
<lastmod>2024-10-25</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
<url>
<loc>https://example.com/blog/post2</loc>
<lastmod>2024-10-24</lastmod>
<changefreq>weekly</changefreq>
<priority>0.8</priority>
</url>
</urlset>
1. Automated XML Generation: With the Django sitemap framework, developers don’t need to
manually create XML sitemaps.
2. Dynamic Sitemaps: The sitemap automatically updates whenever new content is added or
modified.
3. SEO-Friendly: Sitemaps help improve SEO by allowing search engines to efficiently discover
and index content.
Module-5
SOLUTION
1. JavaScript:
2. XMLHttpRequest:
o A built-in browser object used to send HTTP requests and receive responses from a
web server. It supports various formats, including XML, JSON, and plain text.
3. HTML/CSS:
o HTML structures the content of web pages, while CSS styles it. AJAX allows for partial
updates of the HTML content on the page.
o With AJAX, developers can load new content dynamically and style it without a full
page refresh.
4. Server-side Technologies:
o AJAX works with various server-side technologies like PHP, ASP.NET, Ruby on Rails, or
Node.js. These technologies process the requests sent from the client and return
appropriate responses.
o The server can return data in various formats, such as JSON, XML, or HTML.
o Often used as an alternative to XML for data interchange in AJAX applications. JSON
is lightweight and easy to parse in JavaScript, making it a popular choice for modern
web applications.
6. Web APIs:
o AJAX can be used to interact with RESTful APIs, allowing web applications to retrieve
or send data to third-party services asynchronously.
jQuery:
jQuery is a fast, lightweight, and feature-rich JavaScript library that simplifies HTML
document traversal and manipulation, event handling, and animation. One of its primary
benefits is that it abstracts the complexity of JavaScript, making it easier to work with AJAX.
Basic AJAX with jQuery: jQuery provides several methods to make AJAX calls easily. The $.ajax()
method is the most flexible and powerful, but there are also shorthand methods like $.get(), $.post(),
and $.getJSON() for simpler use cases.
1. GET Request:
$.ajax({
url: 'https://api.example.com/data',
type: 'GET',
success: function(response) {
console.log(response);
},
console.error('Error:', error);
});
2. POST Request:
$.ajax({
url: 'https://api.example.com/data',
type: 'POST',
success: function(response) {
},
console.error('Error:', error);
});
SOLUTION
JavaScript: JavaScript is a high-level, dynamic, and interpreted programming language that is a core
technology of the World Wide Web, alongside HTML and CSS. It allows developers to create
interactive and dynamic web applications. Key features of JavaScript include:
Client-Side Scripting: JavaScript runs in the user's browser, enabling dynamic content
updates without requiring page reloads.
Event Handling: It allows developers to respond to user actions like clicks, form submissions,
and keyboard input.
DOM Manipulation: JavaScript can manipulate the Document Object Model (DOM), enabling
changes to the content and structure of web pages.
XMLHttpRequest (XHR): XMLHttpRequest is a built-in JavaScript object that allows web applications
to send HTTP requests and receive responses asynchronously without reloading the page. It is a
fundamental component of AJAX (Asynchronous JavaScript and XML) and plays a crucial role in
modern web development. Key features include:
Asynchronous Communication: XHR enables web pages to send requests to the server and
receive responses without blocking the user interface, enhancing user experience.
Support for Various Data Formats: It can handle different response formats, including JSON,
XML, HTML, and plain text.
Cross-Origin Requests: XHR can be used to make requests to servers other than the one that
served the web page, although this is subject to the same-origin policy for security reasons.
responseXML: Contains the response data as an XML Document if the response was XML.
responseJSON: If the response is in JSON format, it can be parsed into a JavaScript object
using JSON.parse(). This property is not directly available; instead, you convert responseText
to JSON.
10b. Illustrations
CSS is a stylesheet language used to describe the presentation of a document written in HTML or
XML. It controls the layout, colors, fonts, and overall appearance of web pages.
Example:
body {
background-color: #f0f0f0; /* Light grey background */
h1 {
.button {
JSON is a lightweight data interchange format that is easy for humans to read and write and easy for
machines to parse and generate. It is often used for data exchange between a server and a web
application.
Example:
"age": 30,
"isStudent": false,
"address": {
"city": "Anytown",
"zipcode": "12345"
}
iii) HTML (Hypertext Markup Language)
HTML is the standard markup language used to create web pages. It structures content on the web
and is the foundation of any web application.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Sample Page</title>
</head>
<body>
<h1>Welcome to My Website</h1>
</body>
</html>
An iframe is an HTML element that allows you to embed another HTML page within the current
page. It is commonly used to display content from another website or to include external resources.
Example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Iframe Example</title>
</head>
<body>
<h1>Embedded Content</h1>
</html>