21CS62 Set1
21CS62 Set1
USN
Sixth Semester B.E. Degree Examination
Subject Title: Fullstack Development
Note: 1. Answer any FIVE full questions, choosing at least ONE question from each
MODULE. THESE ANSWERS FROM TEXTBOOK
*Bloom’s COs
Module -1 Taxonomy Marks
DOWNLOAD Level
Additional Notes:
- Django, as a web framework, exemplifies modern web
development practices by offering clear separation of
concerns, reusability, and scalability features.
- The Model-View-Controller (MVC) design pattern is
commonly followed in web frameworks like Django to
separate data, logic, and presentation layers for better
maintainability and flexibility.
b Explain how Django Processes a Request. L2 1 10
Answer
How Django Processes a Request
Overview
Django processes a request by following a series of steps
that involve determining the root URLconf, matching the
requested URL with URLpatterns, calling the associated
view function, and converting the HttpResponse to a
proper HTTP response.
Additional Details
- Django starts processing a request by looking for the
settings file, which contains crucial project configurations
like ROOT_URLCONF.
- The ROOT_URLCONF setting specifies the Python
module to be used as the URLconf for the website.
- When a request is made for a specific URL, Django loads
the URLconf pointed to by ROOT_URLCONF and
matches the requested URL with URLpatterns to determine
the appropriate view function to call.
- Once the view function returns an HttpResponse, Django
handles the conversion to a proper HTTP response,
generating the web page for the user.
OR
Q.02 a Explain Wildcard URL patterns and Django’s Pretty Error L2 1 10
Pages.
Page 01 of 02
07082024
21CS62
a quality web application.
- Pretty URLs like '/time/plus/3/' are preferred over query
string parameters like '/time/plus?hours=3' for improved
readability and user experience.
- The Django error page can display detailed information in
special cases such as template syntax errors.
- Developers can leverage the Django error page for
debugging by triggering it with specific code snippets like
'assert False'.
- It is important to avoid exposing sensitive information
through error pages to prevent potential security risks and
reverse engineering attempts.
Summary
Wildcard URL patterns in Django allow for flexible and
dynamic URL matching using regular expressions. Django
promotes the use of clean and aesthetically pleasing URLs
for better user experience. The Django error page serves as a
tool for debugging and handling errors while emphasizing
the importance of securing sensitive information. URL
configuration in Django involves mapping URL patterns to
view functions in the URLconf for efficient request handling
and response generation.
```bash
django-admin startproject myproject
cd myproject
```
```bash
python manage.py startapp time_offset
```
```python
from django.shortcuts import render
from datetime import datetime, timedelta
def time_offset_view(request):
Get current date and time
now = datetime.now()
context = {
'current_time': now,
'four_hours_ahead': four_hours_ahead,
'four_hours_before': four_hours_before,
}
```html
<!DOCTYPE html>
<html>
<head>
<title>Time Offset</title>
</head>
<body>
<h1>Current Date and Time</h1>
<p>{{ current_time }}</p>
```python
from django.urls import path
from .views import time_offset_view
urlpatterns = [
path('', time_offset_view, name='time_offset'),
]
```
```python
from django.contrib import admin
from django.urls import path, include
Page 01 of 02
07082024
21CS62
urlpatterns = [
path('admin/', admin.site.urls),
path('time_offset/', include('time_offset.urls')),
]
```
```bash
python manage.py runserver
```
This setup will display the current date and time along
with the times offset by four hours in both directions.
Module-2
DOWNLOAD
Q. 03 a Explain Basic Template Tags and Filters. L2 2 10
Filters
Page 01 of 02
07082024
21CS62
- Filters provide a convenient way to modify the formatting
of a variable in Django templates.
- Example of a filter: `{{ ship_date|date:"F j, Y" }}` where
the `date` filter formats the `ship_date` variable according to
the specified format.
- Django templates offer built-in filters like `addslashes`,
`date`, and `length` for various formatting and manipulation
tasks.
Template Tags
- Django template system includes built-in tags like `if/else`
for conditional logic.
- The `if` tag evaluates a variable, displaying content based
on its truth value.
- Example:
```
{% if today_is_weekend %}
<p>Welcome to the weekend!</p>
{% endif %}
```
Filter Arguments
- Some filters accept arguments that come after a colon and
are enclosed in double quotes.
- Example: `{{ bio|truncatewords:"30" }}` displays the first
30 words of the `bio` variable.
Additional Information
- Django templates support creating custom tags and filters
for more specialized requirements.
- Appendix F in the Django documentation contains a
comprehensive list of tags and filters available in Django
templates.
2. Template (T):
- Represents the presentation layer.
- In Django, the portion that decides how data should be
displayed on a web page or other documents.
- Contains presentation-related decisions.
3. View (V):
- Represents the business logic layer.
- In Django, the logic that accesses the model and
determines which template(s) to use.
- Acts as a bridge between models and templates.
OR
Q.04 a Explain Template Inheritance with example. L2 2 10
```html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML
4.01//EN">
<html lang="en">
<head>
<title>{% block title %}{% endblock %}</title>
</head>
<body>
<h1>My helpful timestamp site</h1>
{% block content %}{% endblock %}
{% block footer %}
<hr>
<p>Thanks for visiting my site.</p>
{% endblock %}
</body>
</html>
```
Page 01 of 02
07082024
21CS62
Benefits of Template Inheritance
1. Reduction of Redundancy : Avoids duplication of
common page elements.
2. Customization Per Page : Enables flexibility in
modifying specific sections for individual pages.
3. Maintainability : Simplifies updates and changes by
centralizing common components in the base template.
4. Structured Design : Promotes a systematic approach to
organizing templates for efficient web development.
Page 01 of 02
07082024
21CS62
Module-3
DOWNLOAD
Q. 05 a Explain Customizing the Admin Interface. L2 3 10
Benefits of Customization
- Efficiency * *: Customizing the admin interface
streamlines data management processes, increasing
efficiency for site administrators.
- Usability : Tailoring the interface to display relevant
information enhances user experience and simplifies
navigation.
Page 01 of 02
07082024
21CS62
- Security : User permissions control ensures data security
by limiting access to sensitive areas of the admin interface.
Use Cases
- Content Producers and Programmers Collaboration :
Facilitates simultaneous work between content producers
and programmers by providing an intuitive data entry
platform.
- Non- Technical Data Entry : Ideal for scenarios where
non-technical users need to enter data efficiently, making it
a valuable tool for various industries.
Recommendations
- Exploration : Even if not intending to use the Django
admin site, exploring its features can introduce valuable
concepts applicable to other aspects of Django
development.
- Customization : Leveraging customization options can
significantly enhance the user experience and efficiency of
data management tasks within the admin interface.
Page 01 of 02
07082024
21CS62
Processing the Submission
1. Form Submission Handling :
- Checking if the request method is 'POST' to isolate form
submission cases from mere form display.
- Accessing submitted form data using request.POST
when the view is accessed via POST.
2. Data Validation :
- Validating required fields like subject and message,
handling missing keys and data appropriately.
- Fragile email validation by checking for the presence of
'@', with Django offering more robust validation options.
3. Sending Email :
- Using `django.core.mail.send_mail` function to send an
email with required arguments like subject, body, and
sender address.
4. Redirecting After Successful Submission : Best practice
in web development is to issue a redirect for successful
POST requests.
Additional Notes
- Complex Forms : While simple forms can be handled
without using Django's form library, more complex forms
like feedback forms benefit from utilizing the form
framework.
- Error Handling : Validation errors should prompt a
redisplay of the form with previously submitted data to aid
users in correcting mistakes.
OR
Q. 06 a Develop a Model form for student that contains his topic L2 3 10
chosen for project, languages used and duration with
a model called
project.
Page 01 of 02
07082024
21CS62
```python
from django.db import models
class Project(models.Model):
topic = models.CharField(max_length=200)
languages_used = models.CharField(max_length=200)
duration = models.DurationField()
def __str__(self):
return self.topic
```
```python
from django import forms
from .models import Project
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ['topic', 'languages_used', 'duration']
```
Page 01 of 02
07082024
21CS62
1. Open your app's `views.py` file.
```python
from django.shortcuts import render, redirect
from .forms import ProjectForm
def project_view(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
form.save()
return redirect('project_success')
else:
form = ProjectForm()
```html
<!DOCTYPE html>
<html>
<head>
<title>Project Form</title>
</head>
<body>
<h1>Submit Your Project</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</body>
</html>
Page 01 of 02
07082024
21CS62
```
5. Configure URLs
```python
from django.urls import path
from .views import project_view
urlpatterns = [
path('project/', project_view, name='project_form'),
path('success/', lambda request: render(request,
'success.html'), name='project_success'),
]
```
```html
<!DOCTYPE html>
<html>
<head>
<title>Success</title>
</head>
<body>
<h1>Project Submitted Successfully!</h1>
<p>Thank you for submitting your project.</p>
</body>
</html>
```
```bash
python manage.py makemigrations
python manage.py migrate
Page 01 of 02
07082024
21CS62
```
```bash
python manage.py runserver
```
Next Steps
- Chapter 9 will delve into advanced tips and tricks for
Django's template system.
Page 01 of 02
07082024
21CS62
Module-4
DOWNLOAD
Q. 07 a Define Generic Views and explain its types. L2 4 10
5. Customizing Responses :
- Enables modifying the response returned by generic
views.
- Example: Providing a downloadable plain-text version
of a list of authors with specific HTTP headers like
`Content-Disposition`.
Page 01 of 02
07082024
21CS62
OR
Q. 08 a For student’s enrolment, create a generic class view which L2 4 10
displays
list of students and detail view that displays student details
for any selected student in the list.
```python
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
enrollment_number =
models.CharField(max_length=50, unique=True)
course = models.CharField(max_length=100)
date_of_birth = models.DateField()
def __str__(self):
return self.name
```
```python
from django.views.generic import ListView, DetailView
from .models import Student
```
```python
class StudentListView(ListView):
Page 02 of 02
07082024
21CS62
model = Student
template_name = 'students/student_list.html'
context_object_name = 'students'
```
```python
class StudentDetailView(DetailView):
model = Student
template_name = 'students/student_detail.html'
context_object_name = 'student'
```
```python
from django.urls import path
from .views import StudentListView, StudentDetailView
```
3. Define the URL patterns for the list and detail views.
```python
urlpatterns = [
path('students/', StudentListView.as_view(),
name='student_list'),
path('students/<int:pk>/', StudentDetailView.as_view(),
name='student_detail'),
]
```
Page 02 of 02
07082024
21CS62
Creating `student_list.html`
```html
<!DOCTYPE html>
<html>
<head>
<title>Student List</title>
</head>
<body>
<h1>List of Students</h1>
<ul>
{% for student in students %}
<li><a href="{% url 'student_detail' student.pk
%}">{{ student.name }}</a></li>
{% endfor %}
</ul>
</body>
</html>
```
Creating `student_detail.html`
```html
<!DOCTYPE html>
<html>
<head>
<title>{{ student.name }} - Details</title>
</head>
<body>
<h1>Details for {{ student.name }}</h1>
<p>Enrollment Number: {{ student.enrollment_number
}}</p>
<p>Course: {{ student.course }}</p>
<p>Date of Birth: {{ student.date_of_birth }}</p>
<a href="{% url 'student_list' %}">Back to Student
List</a>
</body>
</html>
Page 02 of 02
07082024
21CS62
```
```bash
python manage.py makemigrations
python manage.py migrate
```
```bash
python manage.py runserver
```
Cookies
- Definition : Cookies are small pieces of data stored on
a user's device by websites to remember user
information or track user behavior.
- Purpose : Used for authentication, session
management, personalization, tracking, and analytics. -
Types : Session cookies (temporary), persistent cookies
(remain until deleted or expired), secure cookies (
transmitted over HTTPS), third-party cookies (from
external domains).
- Regulations : Subject to data privacy laws like
Page 02 of 02
07082024
21CS62
GDPR, requiring user consent for non-essential cookies.
Page 02 of 02
07082024
21CS62
Module-5
DOWNLOAD
Q. 09 a List and explain the technologies Ajax is overlaid on. L2 5 10
JavaScript
- JavaScript is the primary technology that Ajax is overlaid
on.
- Ajax runs JavaScript as its engine, working with various
components such as XMLHttpRequest, HTML, CSS, DOM,
XML, JSON, and more.
XMLHttpRequest
- XMLHttpRequest is a crucial component for Ajax
functionality.
- It is used to make asynchronous requests to the server
without needing to reload the entire web page.
CSS
- Cascading Style Sheets (CSS) are utilized in conjunction
with JavaScript for styling and formatting web content
dynamically in Ajax applications.
JSON
- JavaScript Object Notation (JSON) is commonly used with
Ajax in place of XML for data interchange.
- JSON is lightweight and efficient for transmitting data
between the client and server in Ajax applications.
Other Technologies
- Ajax can also work with additional technologies beyond the
core ones mentioned above, depending on specific application
requirements.
- AJAX can be implemented in conjunction with various
server-side technologies to create interactive and responsive
web applications.
Page 02 of 02
07082024
21CS62
Conclusion
Ajax is a technique overlaid on multiple client-side
technologies, primarily JavaScript, that enables dynamic web
content updates without full page reloads. By leveraging
technologies like XMLHttpRequest, HTML, CSS, JSON, and
others, Ajax enhances user experience and interactivity on
web pages.
2. jQuery Integration :
- jQuery is highlighted as the most common JavaScript
library used in conjunction with Django for web
development.
- It is noted for its ease of use and designed to facilitate
powerful results with simplicity, similar to Python's
approach.
3. Ajax Functionality :
- Ajax is described as a technique overlaid on top of
existing technologies, not a standalone technology.
- It enables asynchronous communication between the
client and server, enhancing user experience by allowing
data retrieval without a full page reload.
4. Application Development :
- The chapters in the document outline a detailed case
study on building a Django Ajax web application using
jQuery.
Page 02 of 02
07082024
21CS62
- Topics covered include validating form input on the
server side using Ajax requests, server-side database
searches with Ajax, and more.
5. Separation of Concerns :
- The integration of XHTML Http Request and Response
in web development emphasizes the separation of concerns
between presentation and logic.
- This separation allows for efficient handling of data
exchange between the client and server.
7. jQuery's Facilitation :
- jQuery simplifies the process of making Http requests
from the client side, enabling smoother interaction with the
server.
- Its integration with the Django templating engine
enhances the efficiency of rendering dynamic content based
on server responses.
Conclusion
XHTML Http Request and Response play a significant role
in modern web development, particularly when integrated
with technologies like jQuery and Django. By leveraging
these components effectively, developers can create
interactive and dynamic web applications with efficient data
exchange capabilities.
OR
Page 02 of 02
07082024
21CS62
Q. 10 a List and explain the jQuery Ajax facilities. L2 5 10
Overview
jQuery provides various Ajax facilities to enhance web
applications by enabling asynchronous communication
between the client and server. These facilities offer
efficient ways to handle data retrieval, form submissions,
and dynamic content updates without reloading the entire
web page.
1. $.ajax() Method :
- The foundational and low-level workhorse in jQuery for
making Ajax requests.
- Allows customization of request parameters such as
data, error handling, and success callbacks.
- Default values can be set using $.ajaxSetup().
3. Error Handling :
- Implement error handling mechanisms to manage Ajax
request failures effectively.
- Utilize error callbacks within Ajax requests to display
error messages or handle specific error scenarios.
- Global error handling can be set up using
$.ajaxSetup({error: myErrorHandler}).
4. Server-Side Validation :
- Validate form input on the server side using Ajax
requests sent via jQuery.
- Ensure secure validation practices to verify input data
integrity and prevent malicious or invalid submissions.
Page 02 of 02
07082024
21CS62
6. Authentication and Account Management :
- Implement Ajax-based authentication processes for user
sign-up and login functionalities.
- Explore client-side communication with the server to
handle authentication updates dynamically.
Conclusion
jQuery's Ajax facilities offer a robust toolkit for developers
to create interactive and responsive web applications with
seamless data exchange between the client and server.
```bash
django-admin startproject student_course_search
cd student_course_search
```
```bash
python manage.py startapp courses
```
Page 02 of 02
07082024
21CS62
3. Add the `courses` app to the `INSTALLED_APPS` in
`settings.py`:
```python
INSTALLED_APPS = [
Other installed apps...
'courses',
]
```
```python
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=100)
enrollment_number =
models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
class Course(models.Model):
student = models.ForeignKey(Student,
related_name='courses', on_delete=models.CASCADE)
course_name = models.CharField(max_length=100)
def __str__(self):
return self.course_name
```
```bash
python manage.py makemigrations
python manage.py migrate
```
```python
Page 02 of 02
07082024
21CS62
from django.http import JsonResponse
from django.shortcuts import render
from .models import Student
def search_student_courses(request):
if request.is_ajax():
query = request.GET.get('query', None)
if query:
student =
Student.objects.filter(name__icontains=query).first()
if student:
courses =
student.courses.all().values('course_name')
courses_list = list(courses)
return JsonResponse({'courses': courses_list},
status=200)
return JsonResponse({'courses': []}, status=200)
return JsonResponse({'error': 'Invalid request'},
status=400)
```
```python
def search_page(request):
return render(request, 'courses/search.html')
```
```python
from django.urls import path
from .views import search_student_courses, search_page
urlpatterns = [
path('search/', search_page, name='search_page'),
path('search/courses/', search_student_courses,
name='search_student_courses'),
]
```
```python
Page 02 of 02
07082024
21CS62
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('courses/', include('courses.urls')),
]
```
```html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Student Course Search</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jque
ry.min.js"></script>
</head>
<body>
<h1>Search Courses by Student Name</h1>
<input type="text" id="studentName"
placeholder="Enter student name">
<button id="searchBtn">Search</button>
<h2>Courses Enrolled:</h2>
<ul id="courseList"></ul>
<script>
$(document).ready(function(){
$(' searchBtn').click(function(){
var query = $(' studentName').val();
$.ajax({
url: '{% url "search_student_courses" %}',
data: {'query': query},
dataType: 'json',
success: function(data){
$(' courseList').empty();
if (data.courses.length > 0) {
$.each(data.courses, function(index,
course){
Page 02 of 02
07082024
21CS62
$(' courseList').append('<li>' +
course.course_name + '</li>');
});
} else {
$(' courseList').append('<li>No courses
found for this student.</li>');
}
}
});
});
});
</script>
</body>
</html>
```
```bash
python manage.py runserver
```
2. Navigate to `http://127.0.0.1:8000/courses/search/` in
your browser.
Summary
Page 02 of 02
07082024