0% found this document useful (0 votes)
7 views

Solution 2

Uploaded by

rashmi
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)
7 views

Solution 2

Uploaded by

rashmi
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/ 20

JSSACADEMYOFTECHNICALEDUCATION

JSS Campus, Dr.Vishnuvaradhan Road, Bengaluru-60

Department of Computer Science& Engineering

Scheme and solution-IA 3

Course Name :Full Stack Development CourseCode:21CS62


Course Year(Term) :2023-24 Date:29/07/2024
Course Faculty Name :BNR,VKB, SBN Time:2:00to3:30PM
Semester/Section :6thCSEA,B&C Max.Marks:40

QNo CO’s Solution Mark


s
Explain the different ways of extending Generic views in Django.
In most projects, however, there comes a moment when the generic views no longer suffice.
Indeed, the most common question asked by new Django developers is how to make
C 1 generic views handle a wider array of situations.
31
0. Making “Friendly” Template Contexts
4 We can change the name of that variable easily with the template_object_name argument:
publisher_info = {"queryset" : Publisher.objects.all(),
"template_object_name" : "publisher",}
urlpatterns = patterns('',(r'^publishers/$', list_detail.object_list, publisher_info))
Adding Extra Context
Often you simply need to present some extra information beyond that provided by the
generic view. For example, think of showing a list of all the other publishers on each
publisher detail page. The object_detail generic view provides the publisher to the context,
but it seems there’s no way to get a list of all publishers in that template.
publisher_info = {"queryset" : Publisher.objects.all(),
"extra_context" : {"publisher_list" : Publisher.objects.all()}}
This would populate a {{ publisher_list }} variable in the template context.
This pattern can be used to pass any information down into the template for the generic
view.
Viewing Subsets of Objects
Most generic views take one of these query set arguments—it’s how the view knows which
set of objects to display.
To pick a basic example, we might want to order a list of books by publication date, with
the most recent first:
book_info = {"queryset" : Book.objects.all().order_by("-publication_date"),}

If you want to present a list of books by a particular publisher, you can use the same
technique:
apress_books = {"queryset": Book.objects.filter(publisher__name="Apress Publishing"),
"template_name" : "books/apress_list.html"}
urlpatterns = patterns('', (r'^publishers/$', list_detail.object_list, publisher_info),
(r'^books/apress/$', list_detail.object_list, apress_books),)

Complex Filtering with Wrapper Functions


Earlier we hard-coded the publisher’s name in the URLconf, but what if we wanted to write
a view that displayed all the books by some arbitrary publisher? We can “wrap” the
object_list generic view to avoid writing a lot of code by hand. As usual, we’ll start by
writing a URLconf:
urlpatterns = patterns('', (r'publishers/$', list_detail.object_list, publisher_info),
(r'books/(w+)/$', books_by_publisher), )
OR
Create a generic class view which displays list of students and Detail view that displays
student details for any selected student in the list.

C31 2 Write short notes on i) iFrames ii) Turning on Ajax behavior.


0.5 i) iFrames
Ajax includes several variations; Comet for instance, is a variation on standard Ajax in
which either an XMLHttpRequest object's connection to a server is kept open and
streaming indefinitely, or a new connection is opened whenever an old one is closed,
creating an Ajax environment in which the server as well as the client can push material.
Comet and iframes are two of many possible variations on the basic Ajax technique; what
qualifies as Ajax is more a matter of Python- or JavaScript-style duck-typing than Java-
style static typing. "Asynchronous JavaScript and XML" describes a reference example
more than a strict definition, and it is not appropriate to say "if you replace XML with
JSON then, by definition, it isn't really Ajax." This is a case of, "the proof of the pudding is
in the eating," not what technologies or even techniques are in the kitchen
Example:
Partial page refreshes that look consistent with Ajax DOM manipulations:
 Click on Compose Mail, or a filter, or a message subject, looks very much
like an Ajax update where the Gmail web application talks with the server
if it needs to, and then updates the DOM in accordance with your clicks.
However, there is one important difference between Gmail's behavior and a
similar Ajax clone that updates the DOM for one frameless web page
 Click the browser "Back" button. Normally, if you click on a link, you
trigger an Ajax event but not a whole page refresh, and Ajax optionally
communicates with a server and updates some part of the DOM. This does
not register in the browser's history, and hitting the Back button would not
simply reset the last Ajax partial page update.
 If you made an Ajax clone of Gmail that used DOM manipulations instead
of seamlessly integrated iframes, there would be one important difference
in using the clone: hitting Back would do far more than reverse the last
DOM manipulation.
 It would take you back to the login or load screen. In Gmail, the browser's
Back button works with surgical accuracy, and the reason it can do
something much better than take you back to the login screen is that Gmail
is carefully implemented with iframes, and every change that the Back
button can undo is implemented by a fresh page load in one of the
seamlessly integrated iframes.

ii)Turning on Ajax behavior


We make auto completes out of the relevant selects, and also display
the selects, which the combobox() call hides by default. The user now
has a choice between the select and an auto complete box.
(function()
{ (".autocomplete").combobox();
(".autocomplete").toggle();

Here we have code which, from the documentation, might be


expected to call the update_autocomplete() event handler when a
selection or change is made. However, at this point we encounter a
bend in the road. The bend in the road is this: the following
commented code, when uncommented, doesn't seem to be able to
trigger the handler being called. When it was uncommented, and an
alert() placed at the beginning of update_autocomplete(), the alert() was
not triggered even once. And the usual suspects in terms of forums
and even filing a bug did not succeed in getting the handler to be
called. The alert()was still not called. After this code, let's look at our
updated code on the server side, and then see how this bend in the
road can be addressed.

/*
$(".autocomplete").autocomplete({select: update_autocomplete});
$(".autocomplete").bind({"autocompleteselect": update_autocomplete});
$(".autocomplete").bind({"autocompletechange": update_autocomplete});
*/
});

Now let us turn our attention to the server side.


OR
Explain auto complete and progressive enhancement features of jQuery with examples.
Specific theme can be used is customizable, but autocomplete and
other plugins require some theme such as jQuery UI Themeroller
provides. jQuery UI Themeroller, which lets you customize and tweak
a theme (or just download a default), is available at:
http://jqueryui.com/themeroller/

When you have made any customizations and downloaded a theme,


you can unpack it under your static content directory. In our base.html
template, after our site-specific stylesheet, we have added an include
to the jQuery custom stylesheet (note that you may download a
different version number than we have used here).
{% block head_css_site %}<link rel="stylesheet" type="text/css"
href="/static/css/style.css" />
<link rel="stylesheet" type="text/css"
href="/static/css/smoothness/jquery-ui-1.8.2.custom.css" />
{% endblock head_css_site %}

We will be using the jQuery UI combobox, which offers a "progressive


enhancement" strategy by building a page that will still work with
JavaScript off and will be more accessible than building a solution
with nothing but Ajax.

Progressive enhancement, a best practice


"Progressive enhancement," in a nutshell, means that as much as
possible you build a system that works without JavaScript or CSS,
with semantic markup and similar practices, then add appearance
with CSS, and then customize behavior with JavaScript. A textbook
example of customizing behavior is to make a sortable table which is
originally sortable, in Web 1.0 fashion, by clicking on a link in a table
header which will load a version of the table sorted by that link. Then
the links are "hijaxed" by using JavaScript to sort the table purely by
JavaScript manipulations of the page, so that if a user does not have
JavaScript on, clicking on the links loads a fresh page with the table
sorted by that column, and if the user does have JavaScript, the same
end result is achieved without waiting on a network hit. In this case,
we mark up and populate a dropdown menu of available entities,
which the JavaScript will hide and replace with an autocomplete box.
The option tags follow a naming convention of fieldname.id; all the
autocomplete fields are for fields of an entity, and the naming
convention is not directly for the benefit of server-side code, but so
that an event listener knows which field it has been given a value for.

var MeasureClockSkew = function()


{ var that = this;
var lastButtonPress = new Date().getTime();
var registerError = function(XMLHttpRequest, textStatus, errorThrown)
{ $("#results").append("<li class='error'>Error: " + textStatus + "</li>");
$("#button").removeAttr("disabled"); };
var registerSuccess = function(data, textStatus, XMLHttpRequest)
{ try
{ var remote = JSON.parse(data).time;
var halfway = (lastButtonPress + new Date().getTime()) / 2;
var skew = (remote - halfway) / 1000;
$("#results").append("<li class='success'>Estimated clock skew: <span
class='measurement'>" + skew + "</span> seconds.</li>"); }
catch(error)
{ $("#results").append("<li class='error'>Error parsing JSON.</li>"); }

C31 3
De
Li
0.4 a)Define Generic Views and its types

ta
Cr stUp
ilDe
ea Vida
Vile
te ewte
ewte
Vi Vi Vi
ew ew ew
 Generic views in Django are reusable, abstract classes provided by the Django
framework that encapsulate common patterns used in web development.
Using generic views in Django is a powerful way to simplify the creation of
common views for tasks such as displaying database objects, handling form
submissions, and performing CRUD operations. Generic views provide pre-
built functionality for common patterns, reducing the amount of code you
need to write. Here's how to use generic views in Django.
 Class-based generic list view (ListView) — a class that inherits from an
existing view. Because the generic view already implements most of the
functionality we need and follows Django best-practice, we will be able to
create a more robust list view with less code, less repetition, and ultimately
less maintenance.

 Detail View: Detail View refers to a view (logic) to display one instances of
a table in the database. Detail View refers to a view (logic) to display a
particular instance of a table from the database with all the necessary details.
It is used to display multiple types of data on a single page or view, for
example, profile of a user.

Interacting with Non-Html content


 Normally a Django view receives HttpRequest request and returns
HttpResponse
 By using mime-type in the constructor of HttpResponse, one can return Non-
HTML content
 One can return image, XML, CSV, PDF etc by including appropriate mime
type
b)What is MIME and discuss its types
MIME (Multipurpose Internet Mail Extensions) types are a standard way of
indicating the type of data that a file contains on the Internet. MIME types are
used by web servers and browser to interpret and handle different types of files
appropriately. Here are some common MIME types and their

descriptions:
 Text/html: Represents HTML files, which are used to create web pages.
 Text/css: Represents Cascading Style Sheets (CSS) files, which are used to
style HTML documents.
 Application/javascript: Represents JavaScript files, which are used to add
interactivity and dynamic behavior to web pages.
 Image/jpeg: Represents JPEG image files, which are commonly used for
photographs and other images with complex colors and details.
 Image/png: Represents PNG image files, which are commonly used for
images with transparent backgrounds or simple graphics.
 Application/pdf: Represents PDF (Portable Document Format) files, which
are used for documents that need to be displayed and printed consistently
across different platforms.
 Application/json: Represents JSON (JavaScript Object Notation) files, which
are used for exchanging data between a server and a web application.
 Application/xml: Represents XML (eXtensible Markup Language) files,
which are used for storing and transporting structured data.
 Text/plain: Represents plain text files, which contain unformatted text
without any special styling or formatting.
 Audio/mpeg: Represents MP3 audio files, which are commonly used for
storing and playing music and other audio recording
OR
a) Discuss how to create templates for each view with an example. 
1. ListView

View:# views.py

from django.views.generic import ListView

from .models import MyModel

class MyModelListView(ListView):
model = MyModel

template_name = 'myapp/mymodel_list.html'

context_object_name = 'objects'

Template:html

<!-- myapp/templates/myapp/mymodel_list.html -->

<!DOCTYPE html>

<html>

<head>

<title>MyModel List</title>

</head>

<body>

<h1>MyModel List</h1>

<ul>

{% for object in objects %}

<li>{{ object.name }}</li>

{% endfor %}

</ul>

</body>

</html>

2. DetailView

View:

# views.py

from django.views.generic import DetailView

from .models import MyModel

class MyModelDetailView(DetailView):
model = MyModel

template_name = 'myapp/mymodel_detail.html'

context_object_name = 'object'

Template:

<!-- myapp/templates/myapp/mymodel_detail.html -->

<!DOCTYPE html>

<html>

<head>

<title>{{ object.name }}</title>

</head>

<body>

<h1>{{ object.name }}</h1>

<p>{{ object.description }}</p>

</body>

</html>

3. CreateView

View:

# views.py

from django.views.generic import CreateView

from .models import MyModel

from django.urls import reverse_lazy

class MyModelCreateView(CreateView):

model = MyModel

template_name = 'myapp/mymodel_form.html'

fields = ['name', 'description']


success_url = reverse_lazy('mymodel-list')

Template:

<!-- myapp/templates/myapp/mymodel_form.html -->

<!DOCTYPE html>

<html>

<head>

<title>Create MyModel</title>

</head>

<body>

<h1>Create MyModel</h1>

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Save</button>

</form>

</body>

</html>

4. UpdateView

View:

# views.py

from django.views.generic import UpdateView

from .models import MyModel

from django.urls import reverse_lazy

class MyModelUpdateView(UpdateView):

model = MyModel
template_name = 'myapp/mymodel_form.html'

fields = ['name', 'description']

success_url = reverse_lazy('mymodel-list')

Template:

<!-- myapp/templates/myapp/mymodel_form.html -->

<!DOCTYPE html>

<html>

<head>

<title>Update MyModel</title>

</head>

<body>

<h1>Update MyModel</h1>

<form method="post">

{% csrf_token %}

{{ form.as_p }}

<button type="submit">Save</button>

</form>

</body>

</html>

5. DeleteView

View:

# views.py

from django.views.generic import DeleteView

from .models import MyModel

from django.urls import reverse_lazy


class MyModelDeleteView(DeleteView):

model = MyModel

template_name = 'myapp/mymodel_confirm_delete.html'

success_url = reverse_lazy('mymodel-list')

Template:

<!-- myapp/templates/myapp/mymodel_confirm_delete.html -->

<!DOCTYPE html>

<html>

<head>

<title>Delete MyModel</title>

</head>

<body>

<h1>Are you sure you want to delete "{{ object.name }}"?</h1>

<form method="post">

{% csrf_token %}

<button type="submit">Yes, delete</button>

</form>

<a href="{% url 'mymodel-list' %}">Cancel</a>

</body></html>

b) Explain Dynamic CSV using database.


In Django, generating a dynamic CSV from the database involves querying the
database, processing the data,
and then writing it to a CSV file that can be downloaded by the user. Here’s a
step-by-step guide to achieve this:
1. Set Up Your Django Model
First, ensure you have a model from which you want to generate the CSV. For
example, let&#39;s consider a model
named MyModel.
# models.py
from django.db import models
class MyModel(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)

def __str__(self):
return self.name

2. Create the View to Generate CSV


Next, create a view that will handle the CSV generation and download.
# views.py
import csv
from django.http import HttpResponse
from .models import MyModel

def export_mymodel_csv(request):
# Create the HttpResponse object with the appropriate CSV header.
response = HttpResponse(content_type=&#39;text/csv&#39;)
response[&#39;Content-Disposition&#39;]=&#39;attachment;
filename=&quot;mymodel.csv&quot;&#39;

writer = csv.writer(response)
# Write the header row
writer.writerow([&#39;ID&#39;, &#39;Name&#39;, &#39;Description&#39;,
&#39;Created At&#39;])

# Write data rows


for obj in MyModel.objects.all():
writer.writerow([obj.id, obj.name, obj.description, obj.created_at])

return response
3. Configure the URL
Map the view to a URL in your urls.py file.
# urls.py
from django.urls import path
from .views import export_mymodel_csv
urlpatterns = [
path(&#39;export/csv/&#39;,export_mymodel_csv,
name=&#39;export_mymodel_csv&#39;),]
4. Create a Template Link (Optional)
Optionally, create a link in one of your templates to trigger the CSV
download.

<!-- myapp/templates/myapp/index.html -->

<!DOCTYPE html>

<html>
<head>

<title>Export CSV</title>

</head>

<body>

<h1>Export MyModel Data to CSV</h1>

<a href="{% url 'export_mymodel_csv' %}">Download CSV</a>

</body>

</html>

C31 4 Develop a registration page for student enrolment without page refresh using AJAX.
0.5 To create a registration page for student enrollment without page refresh
using AJAX (Asynchronous JavaScript and XML), you can follow these
steps:

Step 1: Set up the Django app and models: First, create a Django app for
student enrollment:
python manage.py startapp enrollment_app
Define the models for Course and Student in
enrollment_app/models.py:
from django.db import models
class Course(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
def __str__(self):
return self.name
class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()
course = models.ForeignKey(Course,
on_delete=models.CASCADE)

def __str__(self):
return self.name
Step 2: Create views and templates for registration: Define views and
templates for the registration form and submission handling. In
enrollment_app/views.py, add the following code:
from django.shortcuts import render
from django.http import JsonResponse
from .models import Course, Student
def registration_page(request):
courses = Course.objects.all()
return render(request, 'enrollment_app/registration.html',
{'courses': courses})
def register_student(request):
if request.method == 'POST':
name = request.POST.get('name')
email = request.POST.get('email')
course_id = request.POST.get('course')
course = Course.objects.get(pk=course_id)
student = Student.objects.create(name=name, email=email,
course=course)
return JsonResponse({'success': True})
return JsonResponse({'success': False})
Create a registration.html template in the
enrollment_app/templates/enrollment_app directory:
<!DOCTYPE html>
<html>
<head>
<title>Student Registration</title>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<h1>Student Registration</h1>
<form id="registration-form">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br>
<label for="course">Course:</label>
<select id="course" name="course" required>
{% for course in courses %}
<option value="{{ course.id }}">{{ course.name
}}</option>
{% endfor %}
</select><br>
<button type="submit">Register</button>
</form>
<div id="message"></div>
<script>
$(document).ready(function() {
$('#registration-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url "register_student" %}',
data: $(this).serialize(),
success: function(response) {
if (response.success) {
$('#message').text('Registration successful!');
$('#registration-form')[0].reset();
} else {
$('#message').text('Error: Registration failed.');
} } }); }); });
</script>
</body>
</html>
Step 3: Define URL patterns and include them in the project's URLs:
Define URL patterns in enrollment_app/urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.registration_page, name='registration_page'),
path('register/', views.register_student, name='register_student'),]
Include these URLs in the project's urls.py file:
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('enrollment/', include('enrollment_app.urls')),]
Step 4: Run migrations and start the server: Apply migrations to create
database tables for the models and start the Django development server:
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Now, you can access the registration page at
http://127.0.0.1:8000/enrollment/ and register students without
page refresh using AJAX. The form will submit the data
asynchronously, and the success or error message will be displayed
without reloading the entire page.

OR
a) Discuss how the setting of Java script in Django.

For the development server, putting static content, including images, CSS,
and static content, is straightforward. For production use, the recommended
best practice is to use a different implementation, and Django users are
advised to use a separate server if possible, optimized for serving static
media, such as a stripped-down build of Apache. However, for development
use, the following steps will serve up static content:
1. Create a directory named static within your project. (Note that other
names may be used, but do not use media, as that can collide with
administrative tools.)
2. Edit the settings.py file, and add the following at the top, after import os:

DIRNAME = os.path.abspath(os.path.dirname(_file_))

3. Change the settings of MEDIA_ROOT and MEDIA_URL:

MEDIA_ROOT = os.path.join(DIRNAME, 'static/'

MEDIA_URL = '/static/'

4. At the end of the settings.py file, add the following:

if settings.DEBUG:

urlpatterns += patterns('django.views.static',(r'^%s(?P<path>.*)$' %
(settings.MEDIA_URL[1:],),'serve',
{'document_root':settings.MEDIA_ROOT,'show_indexes': True }),)

This will turn off static media service when DEBUG is turned off, so that
this code does not need to be changed when your site is deployed live, but
the subdirectory static within your project should now serve up static
content, like a very simplified Apache. We suggest that you create three
subdirectories of static: static/css,static/images, and static/js, for serving up
CSS, image, and JavaScript static content.

b) Develop a search application in Django using AJAX that displays courses


Enrolled by a student being searched.
To create a search application in Django using AJAX that displays courses
enrolled by a student being searched, follow these steps:

Step 1: Set up the Django app and models: First, create a Django app for
the search application:
python manage.py startapp search_app
Define the models for Course and Student in
search_app/models.py:
from django.db import models

class Course(models.Model):
name = models.CharField(max_length=100)

def __str__(self):
return self.name

class Student(models.Model):
name = models.CharField(max_length=100)
courses = models.ManyToManyField(Course)

def __str__(self):
return self.name
Step 2: Create views and templates: Define views and templates to handle
the search functionality and display the results. In search_app/views.py,
create a view for handling the search request:
from django.shortcuts import render
from .models import Student

def search_courses(request):
if request.method == 'GET' and 'student_name' in request.GET:
student_name = request.GET['student_name']
student =
Student.objects.filter(name__icontains=student_name).first()
if student:
courses = student.courses.all()
else:
courses = []
return render(request, 'search_app/course_list.html', {'courses':
courses})
return render(request, 'search_app/search_form.html')
Create two HTML templates in the
search_app/templates/search_app directory:
 search_form.html for the search form.
 course_list.html for displaying the list of courses.
search_form.html:
<!DOCTYPE html>
<html>
<head>
<title>Search Form</title>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js
"></script>
</head>
<body>
<h1>Search for Courses by Student Name</h1>
<form id="searchForm" method="GET">
<label for="studentName">Student Name:</label>
<input type="text" id="studentName" name="student_name">
<button type="submit">Search</button>
</form>
<div id="courseList"></div>

<script>
$(document).ready(function() {
$('#searchForm').on('submit', function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: '{% url "search_courses" %}',
type: 'GET',
data: formData,
success: function(response) {
$('#courseList').html(response);
},
error: function(xhr, errmsg, err) {
console.log(xhr.status + ": " + xhr.responseText);
} }); }); });
</script>
</body>
</html>
course_list.html:
<!DOCTYPE html>
<html>
<head>
<title>Course List</title>
</head>
<body>
<h2>Courses Enrolled by {{ student.name }}</h2>
<ul>
{% for course in courses %}
<li>{{ course.name }}</li>
{% endfor %}
</ul>
</body>
</html>
Step 3: Update URLs: Define URL patterns in search_app/urls.py to map
views to URLs:
from django.urls import path
from . import views

urlpatterns = [
path('', views.search_courses, name='search_courses'),]
Include these URLs in the project's urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('search/', include('search_app.urls')),]
Step 4: Run migrations and start the server: Apply migrations to create
database tables for the models and start the Django development server:
python manage.py makemigrations
python manage.py migrate
python manage.py runserver
Now, you can access the search form in your browser at
http://127.0.0.1:8000/search/ and search for courses enrolled by a
student by entering their name. The results will be displayed using
AJAX without refreshing the page

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy