21CS62 Set2
21CS62 Set2
US
N
Note:
01. Answer any FIVE full questions, choosing at least ONE question from each MODULE
THESE ANSWERS FROM TEXTBOOK
Bloom’s COs
Module -1 Taxonom Marks
DOWNLOA y Level
D
Page 01 of
07082
21CS62
- URLs : Specifies which view is called for a given
URL pattern.
- Templates : HTML files like latest_books.html describe
the page design using a template language.
Page 01 of
07082
21CS62
separation of concerns in web development projects.
Steps Involved:
1. Creating a View Function:
- Views in Django are Python functions that handle web
requests and return web responses.
- View functions are defined in a Python module,
usually named views.py.
- Example:
```
from mysite.views import hello, my_homepage_view
urlpatterns = patterns('',
('^$', my_homepage_view),
...
)
```
Key Points:
- URLpatterns start with carets (^) and end with dollar signs
($).
- Django can redirect URLs that don't match a pattern to
the correct one based on settings like APPEND_SLASH.
- View functions must return an instance of HttpResponse.
- URLconfs in Django serve as a mapping between
URLs and view functions for handling web requests.
Page 01 of
07082
21CS62
5. Code Reusability : Allows for reusing view functions
with different URL mappings, enhancing code efficiency.
Conclusion
Loose coupling in Django URLConfs plays a vital role in
promoting flexibility, maintainability, and extensibility
in Django web applications. By separating URL
definitions from view functions, developers can make
changes independently, leading to a more modular and
scalable codebase.
OR
Page 01 of
07082
21CS62
interactions and inputs.
2. Backward Compatibility :
- Django developers ensure backward compatibility within
major version numbers.
- Applications written for Django 1.1 are expected to
work with versions like 1.2, 1.3, and 1.9, but potential
rewrites may be necessary when major version changes
occur.
Page 01 of
07082
21CS62
first parameter and return an instance of HttpResponse.
- Views are responsible for processing requests and
returning responses to clients.
- Views are defined in the `views.py` file within a
Django project.
- URLs in Django are mapped to specific views
through URLconf.
Page 01 of
07082
21CS62
Module-2
DOWNLOAD
Page 01 of
07082
21CS62
- The template system has roots in the web development
Page 01 of
07082
21CS62
practices at World Online and the experience of Django's
creators.
- Django's template language design philosophy and features
set it apart from other template systems.
Installing Models
- After defining models, tables need to be created in the
database to store the data.
- Activating models in a Django project involves adding the
Page 01 of
07082
21CS62
app containing the models to the list of "installed apps" in
the settings file.
Page 01 of
07082
21CS62
- The process of installing models includes creating
the necessary database tables based on the defined
models.
Additional Information
- Understanding basic relational database theory and SQL is
recommended when working with Django's database layer.
- Django provides tools for performing database queries
using Python, making it suitable for database-driven
web applications.
- Django's database layer simplifies the interaction with
database servers, data retrieval, and data presentation on
web pages.
1. Manual Synchronization :
- Ensure manual synchronization between Django models
and the database schema to prevent inconsistencies.
- Regularly update the database structure based on
changes in Django models to maintain data
integrity.
2. Automatic Introspection :
- Utilize Django's introspection capabilities to generate
models from an existing database, simplifying the setup
process.
- Be aware of the overhead and limitations of
runtime database introspection, especially with older
database versions.
Summary
Schema evolution in Django involves adjusting database
schemas to align with application changes. Django
simplifies this process by storing data models as code,
offering introspection utilities, and emphasizing the
importance of maintaining consistency between models and
the database structure.
Page 01 of
07082
21CS
OR
Levels of Inheritance
- Three-Level Approach :
1. Base.html for main site structure.
2. Base_SECTION.html for section-specific styles.
Page 02 of
07082
21CS
3. Individual templates for specific page types.
Additional Information
Page 02 of
07082
21CS
- Context Preservation : Template inheritance does not
affect the template context, providing access to all
template variables in the inheritance tree.
Inserting Data:
1. Instantiating Model Class : Create an instance of
the model class with the desired data values.
2. Saving Data to Database : Call the `save()` method to
insert the record into the database.
3. Example SQL Translation :
- Initial Insert: `INSERT INTO books_publisher (name,
address, city, state_province, country, website) VALUES
('Apress', '2855 Telegraph Ave.', 'Berkeley', 'CA', 'U.S.A.',
'http://www.apress.com/');`
- Handling Autoincrementing Primary Key: Django
calculates and sets the primary key value upon
saving.
4. Subsequent Updates : Modify data attributes and call
` save()` to update the existing record in the database.
Updating Data:
1. Changing Object Attributes : Update the attributes of the
Page 02 of
07082
21CS
existing object.
Page 02 of
07082
21CS
2. Saving Changes : Use the `save()` method to update the
record in the database.
3. SQL Translation for Update :
- Example Update Statement: `UPDATE books_publisher
SET name = 'Apress Publishing', address = '2855 Telegraph
Ave.', city = 'Berkeley', state_province = 'CA', country =
'U.S.A.', website = 'http://www.apress.com' WHERE id =
52;`
4. Instant Update : Subsequent calls to `save()` perform an
SQL UPDATE statement to modify existing data.
Additional Notes:
- Primary Key Handling : Django automatically assigns an
autoincrementing integer primary key field called `id` to
each model unless explicitly defined.
- Validation : Models can be validated using the `python
manage.py validate` command to ensure correct syntax and
logic.
```python
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
class Author(models.Model):
first_name = models.CharField(max_length=30)
Page 02 of
07082
21CS
last_name = models.CharField(max_length=40)
email = models.EmailField()
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
Why It Is Useful:
- The ` unicode ()` method allows you to customize how
Django represents objects as strings.
- It provides a more informative and human-
readable representation of model instances.
- Improves the readability of objects when displayed in
lists or other contexts within Django.
Page 02 of
07082
21CS
Module-3
DOWNLOAD
Powerful Features
- Django's admin interface reads metadata from models to
generate a robust and production-ready interface.
- It offers features like customizable list displays, filtering
options, date hierarchy, and field ordering for efficient data
management.
- Users can activate, use, and customize the admin
interface with just a few lines of code.
User-Friendly Interface
- Designed for nontechnical users, the Django admin site is
intuitive and user-friendly.
- It includes a login screen for user authentication and
provides a clear overview of available data types for editing.
- Users can easily navigate through the admin site to
manage data efficiently.
Customization Options
- Django's admin interface offers customization options such
as field exclusion, list display configuration, and filter
Page 02 of
07082
21CS
settings.
Page 02 of
07082
21CS
- Users can tailor the admin interface to suit their
specific data-entry workflows and user roles.
- Customization features enhance the user experience and
streamline data management processes.
Process Overview:
To create and process feedback forms in Django, follow
these steps:
```python
from django import forms
Page 02 of
07082
21CS
class ContactForm(forms.Form):
subject = forms.CharField(max_length=100)
e-mail = forms.EmailField(required=False)
message = forms.CharField(widget=forms.Textarea)
def clean_message(self):
message = self.cleaned_data['message']
num_words = len(message.split())
if num_words < 4:
raise forms.ValidationError("Not enough words!")
return message
```
Page 02 of
07082
21CS
OR
Additional Steps
1. Set up permissions for users based on their roles.
2. Customize user accounts through the admin interface.
3. Integrate user accounts with the rest of the site for
broader functionality.
Page 02 of
07082
21CS
URLConf tricks in Django refer to techniques and strategies
employed in URL configuration to enhance flexibility and
maintainability. They are utilized to streamline function
imports, manage URL patterns efficiently, and improve
readability. One specific aspect of URLConf involves using
named groups instead of non-named groups. Named groups
provide advantages such as explicitness, improved argument
order management, and enhanced readability. They allow
for capturing URL parameters and passing them as keyword
arguments to view functions, making the URLConf more
structured and easier to maintain.
Page 02 of
07082
21CS
Module-4
DOWNLOAD
Page 02 of
07082
21CS
b Describe how to generate non-HTML content like CSV L2 CO 10
and PDF using Django. 4
```python
import csv
from django.http import HttpResponse
from .models import Student
def export_students_csv(request):
Create the HttpResponse object with the appropriate
CSV header.
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment;
filename="students.csv"'
writer = csv.writer(response)
writer.writerow(['Name', 'Enrollment Number', 'Course',
'Date of Birth'])
students = Student.objects.all().values_list('name',
'enrollment_number', 'course', 'date_of_birth')
for student in students:
writer.writerow(student)
return response
```
```python
from django.urls import path
Page 02 of
07082
21CS
from .views import export_students_csv
urlpatterns = [
Other URL patterns...
path('export/csv/', export_students_csv,
name='export_students_csv'),
]
```
```bash
pip install reportlab
```
```python
from django.http import HttpResponse
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from .models import Student
def export_students_pdf(request):
Create the HttpResponse object with the appropriate
PDF header.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment;
filename="students.pdf"'
Page 02 of
07082
21CS
Write some text in the PDF.
p.drawString(100, height - 100, "List of Students")
```python
from django.urls import path
from .views import export_students_pdf
urlpatterns = [
Other URL patterns...
path('export/pdf/', export_students_pdf,
name='export_students_pdf'),
]
```
Summary
Cookies in Django:
- Cookies in Django are small pieces of data stored on the
client's machine.
- They are used to store information like session IDs,
user preferences, etc.
- Django uses cookies to maintain sessions and manage
state persistence for users.
Sessions in Django:
- Sessions in Django are a way to store user data on the
server-side.
- They allow maintaining user-specific
information throughout the user's interaction with
the website.
- Django uses sessions to store user authentication details,
shopping cart contents, and other user-specific data
securely.
Page 02 of
07082
21CS
Importance of Cookies and Sessions in Django:
- Cookies and sessions are essential components in web
development for managing user sessions and maintaining
state across requests.
- They enable personalized user experiences, secure
data storage, and efficient session management in
Django applications.
OR
Page 02 of
07082
21CS
Benefits of Using Django's Sitemap Framework
- Simplifies the process of creating and maintaining XML
sitemaps for websites.
Page 02 of
07082
21CS
- Ensures that search engines can efficiently crawl and
index a site's content.
- Provides a structured way to manage the URLs and
content hierarchy of a Django project.
- Enhances SEO by facilitating better visibility
and accessibility for search engine bots.
Feed
To create a syndication feed in Django, you need to define a
custom template tag, specifying how the raw template tag is
converted into a Node (the compilation function) and what
the node's render() method does. The process involves
writing the compilation function for each template tag
encountered, which returns a Node instance based on the tag
contents.
Page 02 of
07082
21CS
4. Node List Representation :
- A compiled template is represented as a list of Node
Page 02 of
07082
21CS
objects.
- Each node represents a specific element in the template
structure.
5. Node Types :
- Text node: Represents text elements in the template.
- Variable node: Represents variables to be rendered.
- IfEqual node: Handles conditional logic in templates.
6. Customization :
- Custom template tags allow for extending the
functionality of Django's template system.
- Tags are more complex than filters and can perform a
wide range of tasks.
Conclusion
Creating a syndication feed in Django involves defining
custom template tags, writing the compilation function for
each tag, and specifying how nodes are rendered within the
template structure. By understanding the compilation and
rendering process, developers can extend Django's template
system to include custom functionality such as syndication
feed generation.
Page 02 of
07082
21CS
2. Authentication Views : Django offers authentication
views such as login, logout, password reset, and
password change views to handle user authentication
processes.
Page 02 of
07082
21CS
5. Backends : Backend customization enables different
authentication methods beyond the default username
and
Page 02 of
07082
21CS
password.
Module-5
DOWNLOAD
Page 02 of
07082
21CS
Q. 09 a What is AJAX and how is it integrated with Django? L2 CO 5
5
AJAX Integration with Django
What is AJAX?
- Ajax is not a standalone technology but a technique
overlaid on other technologies.
- It stands for Asynchronous JavaScript and XML,
although it can be used without JavaScript.
- In analogy, like speech is overlaid on organs with
other functions, Ajax is overlaid on existing
technologies.
- Ajax allows for asynchronous communication between
the client and server without requiring a page refresh.
Page 03 of
07082
21CS
Additional Details
- Ajax is considered a gateway to JavaScript, facilitating the
adoption and utilization of JavaScript in web development.
- Django's templating engine focuses on separating
design and programming aspects, ensuring a user-friendly
development experience.
- jQuery is preferred for its lightweight nature and ease of
use in combination with Django for Ajax functionality.
Page 03 of
07082
21CS
- The combination of jQuery UI Autocomplete and Django
ModelForms offers a powerful toolset for building
dynamic and user-friendly interfaces.
Page 03 of
07082
21CS
Steps for Setting Up JavaScript in Django
1. Static Content Placement :
- Create a directory for static content within the project.
- Update settings.py file with the directory path for static
files.
- Specify MEDIA_ROOT and MEDIA_URL settings
for serving static content.
3. Error Handling :
- Set up default error handlers using $.ajaxSetup() for
Ajax requests.
- Define error handling functions to manage Ajax
errors effectively.
4. Template Modifications :
- Adjust template elements for improved JavaScript
functionality.
- Rename functions as needed for clarity and
functionality enhancements.
Additional Considerations
- Experiment with jQuery and Ajax functionalities to
enhance user interactions in Django applications.
Page 03 of
07082
21CS
- Keep template modifications clear and organized to
maintain code readability and manageability.
OR
XMLHttpRequest in AJAX
1. XMLHttpRequest object is crucial for making
asynchronous requests in AJAX.
2. It allows communication between a web browser and
a server without needing to refresh the entire page.
3. The object is created or reused, a callback event
handler is specified, the connection is opened, data is sent,
and the response is retrieved.
4. It includes methods like `abort()`,
`getAllResponseHeaders()`, and
`getResponseHeader(headerName)` for managing requests.
5. Ensures proper handling of server responses,
HTTP codes, and status descriptions.
Page 03 of
07082
21CS
5. jQuery facilitates cross-browser compatibility and
streamlines AJAX implementation.
5. Security Considerations :
- Ensuring secure iframe usage to prevent malicious code
execution.
- Validating and sanitizing content loaded through
iframes to maintain application security.
6. Optimizing Performance :
- Best practices for optimizing iframe performance in
Django applications.
- Caching strategies and considerations for
improving content loading speed.
Conclusion:
Utilizing iframes in Django provides a flexible and efficient
way to load content dynamically on web pages. By
leveraging iframes effectively, developers can enhance user
experience and streamline the presentation of diverse text
formats within Django applications.
Bloom’s Taxonomy Level: Indicate as L1, L2, L3, L4, etc. It is also desirable to indicate the
COs and POs to be attained by every bit of questions.
Page 03 of
07082