Module 23 - Miscellaneous Content
This module combines essential knowledge for modern web development: utilizing Django's
built-in generic views for updating database entries and mastering the fundamentals of
Bootstrap for responsive front-end design.
Chapter 1: Django Generic Views
1.1 Updating entries in Django with UpdateView
Django's Class-Based Generic Views (CBGVs) are powerful tools that reduce boilerplate
code. UpdateView is specifically designed to handle the display of a form for an existing
object and saving changes to that object.
Purpose: To simplify the process of retrieving an existing object from the database,
populating a form with its data, handling form submission (validation and saving),
and redirecting upon success.
Advantages:
o Less code compared to writing a function-based view for updates.
o Handles common CRUD (Create, Read, Update, Delete) patterns.
o Customizable for specific needs.
Key Attributes/Parameters:
o model: (Required) The Django model that this view will operate on (e.g.,
Post, Product).
o fields: (Required, unless form_class is used) A tuple or list of field names
from the model that should be included in the automatically generated form.
o form_class: (Optional) If you have a custom forms.Form or
forms.ModelForm defined, you can specify it here instead of fields.
o template_name: (Optional) The path to the template to render the form. By
default, Django looks for <app_name>/<model_name>_form.html (e.g.,
blog/post_form.html).
o success_url: (Optional) The URL to redirect to after a successful form
submission. If not provided, Django will try to call the get_absolute_url()
method on the model instance.
o pk_url_kwarg / slug_url_kwarg: (Optional) Specifies the name of the URL
keyword argument that contains the primary key (pk) or slug (slug) of the
object to be updated. Defaults to pk and slug respectively.
Steps to Implement UpdateView:
1. Define a Django Model: Ensure your model exists in models.py.
Python
# myapp/models.py
from django.db import models
from django.urls import reverse
1
class Product(models.Model):
name = models.CharField(max_length=100)
description = models.TextField(blank=True)
price = models.DecimalField(max_digits=10,
decimal_places=2)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
def get_absolute_url(self):
# This is important for UpdateView's default
success_url behavior
return reverse('product_detail', kwargs={'pk':
self.pk})
2. Create a URL Pattern: In your urls.py, define a URL that captures a
primary key (or slug) to identify the specific object to update.
Python
# myproject/urls.py or myapp/urls.py
from django.contrib import admin
from django.urls import path
from myapp.views import ProductUpdateView, ProductDetailView #
Assuming ProductDetailView exists
urlpatterns = [
path('admin/', admin.site.urls),
path('product/<int:pk>/update/',
ProductUpdateView.as_view(), name='product_update'),
path('product/<int:pk>/', ProductDetailView.as_view(),
name='product_detail'), # For get_absolute_url
# ... other paths
]
3. Define the UpdateView in views.py: Inherit from UpdateView and specify
the model and fields.
Python
# myapp/views.py
from django.views.generic.edit import UpdateView
from django.views.generic import DetailView # For
product_detail view
from myapp.models import Product
from django.urls import reverse_lazy # Use reverse_lazy for
success_url in CBV attributes
class ProductUpdateView(UpdateView):
model = Product
fields = ['name', 'description', 'price'] # Fields to show
in the form
template_name = 'myapp/product_form.html' # Custom template
name
success_url = reverse_lazy('product_detail') # Redirect to
product detail page after update
2
# If you want to redirect to the updated object's detail
page
# def get_success_url(self):
# return reverse('product_detail', kwargs={'pk':
self.object.pk})
class ProductDetailView(DetailView):
model = Product
template_name = 'myapp/product_detail.html' # Template to
show product details
4. Create the Template: The template will contain the HTML form. The
UpdateView automatically passes the form instance as a context variable
named form.
HTML
{# myapp/templates/myapp/product_form.html #}
<!DOCTYPE html>
<html>
<head>
<title>Update Product</title>
</head>
<body>
<h1>Update Product: {{ product.name }}</h1> {# 'product' is
the object instance #}
<form method="post">
{% csrf_token %} {# Django's security token for forms
#}
{{ form.as_p }} {# Renders form fields as paragraphs #}
<button type="submit">Update Product</button>
</form>
<p><a href="{% url 'product_detail' pk=product.pk
%}">Cancel</a></p>
</body>
</html>
And a simple detail template for get_absolute_url to work:
HTML
{# myapp/templates/myapp/product_detail.html #}
<!DOCTYPE html>
<html>
<head>
<title>{{ product.name }} Detail</title>
</head>
<body>
<h1>{{ product.name }}</h1>
<p>Description: {{ product.description }}</p>
<p>Price: ${{ product.price }}</p>
<p><a href="{% url 'product_update' pk=product.pk %}">Edit
this product</a></p>
<p><a href="/">Back to list (or wherever)</a></p>
</body>
</html>
3
Customizing the Form: If you need more control over validation or widgets, you can
define a ModelForm and use the form_class attribute instead of fields.
Python
# myapp/forms.py
from django import forms
from myapp.models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'description', 'price']
widgets = {
'description': forms.Textarea(attrs={'rows': 4}),
}
# myapp/views.py (updated)
from myapp.forms import ProductForm
class ProductUpdateView(UpdateView):
model = Product
form_class = ProductForm # Use your custom form
template_name = 'myapp/product_form.html'
success_url = reverse_lazy('product_detail')
Chapter 2: Bootstrap Framework
Bootstrap is the most popular CSS framework for developing responsive, mobile-first
projects on the web. It is a comprehensive collection of pre-written CSS and JavaScript code
that helps you build consistent and professional-looking websites quickly.
2.1 Bootstrap Part 1: Introduction To Bootstrap
What is Bootstrap?
o A free and open-source front-end development framework.
o Contains HTML, CSS, and JavaScript-based design templates for typography,
forms, buttons, navigation, and other interface components.
o Designed for building responsive (adapts to different screen sizes) and mobile-
first websites.
Why use it?
o Speed: Provides ready-to-use components and styles, significantly speeding
up development time.
o Responsiveness: Built-in responsive grid system makes websites look good
on desktops, tablets, and mobile phones automatically.
o Consistency: Ensures a consistent look and feel across different parts of your
website.
o Ease of Use: Relatively easy to learn and implement, especially for basic
layouts and components.
o Community & Documentation: Has a vast community and excellent,
comprehensive documentation.
4
2.2 Bootstrap Part 2: Adding Bootstrap To Our Site
There are several ways to include Bootstrap in your web project. The easiest and most
common for quick setup is using a CDN (Content Delivery Network).
Using CDN (Content Delivery Network):
o A CDN delivers Bootstrap's CSS and JavaScript files from a globally
distributed network of servers. This means faster loading times for users as the
files are fetched from a server geographically closer to them.
o Bootstrap 5 (Current Version): Requires Popper.js for some JavaScript
components (like tooltips, popovers).
To add Bootstrap 5 to your HTML file, place the CSS link in the <head> section and
the JavaScript bundle (which includes Popper) just before the closing </body> tag.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>My Bootstrap Page</title>
<link
href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap
.min.css" rel="stylesheet" integrity="sha384-
QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH"
crossorigin="anonymous">
</head>
<body>
<h1>Hello, Bootstrap!</h1>
<p>This is a paragraph styled by Bootstrap.</p>
<button class="btn btn-primary">Click Me</button>
<script
src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.b
undle.min.js" integrity="sha384-
YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz"
crossorigin="anonymous"></script>
</body>
</html>
Downloading Bootstrap:
o You can also download the compiled CSS and JavaScript files from the
official Bootstrap website (getbootstrap.com) and host them locally on your
server. This gives you more control and works offline, but requires you to
manage the files.
2.3 Bootstrap Part 3: Bootstrap Grid System
The Bootstrap Grid System is the core of its responsive design capabilities. It's built with
Flexbox and allows you to create responsive page layouts easily.
5
Fundamentals:
o 12-Column System: The grid is based on a 12-column layout. You can
combine these columns to create various layouts (e.g., two col-6s for 50/50,
three col-4s for 33/33/33).
o Rows: Columns must be placed inside a row. Rows create horizontal groups
of columns.
o Columns: Content is placed inside columns. Columns add horizontal padding
(gutters) for spacing.
o Containers: Rows must be placed inside a container or container-fluid.
container vs. container-fluid:
o .container: Provides a fixed-width container (max-width changes at each
responsive breakpoint). It centers your content on larger screens.
o .container-fluid: Provides a full-width container, spanning the entire
width of the viewport.
Basic Grid Structure Example:
HTML
<div class="container">
<div class="row">
<div class="col-sm-6">Column 1</div>
<div class="col-sm-6">Column 2</div>
</div>
</div>
<div class="container-fluid">
<div class="row">
<div class="col">Full Width Column</div>
</div>
</div>
2.4 Bootstrap Part 4: Grid Classes Part 1 (Breakpoints)
Bootstrap's grid system scales up to 12 columns as the device or viewport size increases. It
includes five default responsive tiers (breakpoints), which are effectively prefixes for
column classes.
Breakpoints (Screen Sizes):
o xs (extra small): <576px (no prefix needed, e.g., col-4)
o sm (small): >=576px (e.g., col-sm-6)
o md (medium): >=768px (e.g., col-md-4)
o lg (large): >=992px (e.g., col-lg-3)
o xl (extra large): >=1200px (e.g., col-xl-2)
o xxl (extra extra large): >=1400px (e.g., col-xxl-1)
How They Work:
o If you apply a class like col-md-6, it means the column will be 6 units wide
from the medium breakpoint upwards.
o For screens smaller than the md breakpoint, it will stack vertically (take 100%
width) by default.
o You can combine classes for different behaviors at different breakpoints. The
smallest applied breakpoint will take effect from that size upwards.
Example:
6
HTML
<div class="container">
<div class="row">
<div class="col-sm-12 col-md-6 col-lg-4">
Column A
</div>
<div class="col-sm-12 col-md-6 col-lg-4">
Column B
</div>
<div class="col-sm-12 col-md-6 col-lg-4">
Column C (will wrap on medium, stack on small)
</div>
</div>
</div>
2.5 Bootstrap Part 5: Grid Classes Part 2 (Auto Layout & Column Widths)
Beyond explicit column numbers, Bootstrap provides flexible auto-layout options.
.col(Auto-Layout for Equal Widths):
o If you just use col without a number (or a breakpoint prefix), it creates
columns of equal width within a row.
o The number of col elements determines the division.
HTML
<div class="container">
<div class="row">
<div class="col">1 of 2</div>
<div class="col">2 of 2</div>
</div>
<div class="row">
<div class="col">1 of 3</div>
<div class="col">2 of 3</div>
<div class="col">3 of 3</div>
</div>
</div>
.col-auto (Content-Based Width):
o col-auto makes the column's width fit its content, while other col siblings in
the same row will equally divide the remaining space.
HTML
<div class="container">
<div class="row justify-content-md-center">
<div class="col col-lg-2">
1 of 3
</div>
<div class="col-auto">
Variable width content (e.g., a long piece of text)
</div>
<div class="col col-lg-2">
3 of 3
</div>
7
</div>
</div>
Setting Specific Column Widths:
o You can explicitly set column widths using numbers from 1 to 12.
HTML
<div class="container">
<div class="row">
<div class="col-4">One third width</div>
<div class="col-8">Two thirds width</div>
</div>
<div class="row">
<div class="col-3">Quarter width</div>
<div class="col-6">Half width</div>
<div class="col-3">Quarter width</div>
</div>
</div>
2.6 Bootstrap Part 6: Grid Column Offset
Offsets allow you to push columns to the right, effectively creating empty space.
offset-*-* classes:
o Syntax: offset-[breakpoint]-[number_of_columns]
o Pushes a column over by a specified number of columns to the right.
o Uses the 12-column system. For example, offset-md-3 will push the column
by 3 units from the medium breakpoint up.
Example:
HTML
<div class="container">
<div class="row">
<div class="col-md-4 offset-md-4">
This column is 4 units wide and is offset by 4 units.
It will be centered on medium screens and larger.
</div>
</div>
<div class="row">
<div class="col-md-3">First column</div>
<div class="col-md-3 offset-md-6">Last column (pushed by
6)</div>
</div>
</div>
2.7 Bootstrap Part 7: Making Images Responsive
Bootstrap provides utility classes to ensure images scale correctly across different devices
without overflowing their parent containers.
img-fluid:
o This is the primary class for responsive images.
8
o It applies max-width: 100%; and height: auto; to the image. This ensures
the image never exceeds the width of its parent element and scales down
proportionally when the viewport is smaller.
HTML
<div class="container">
<div class="row">
<div class="col-md-6">
<img src="your-image.jpg" class="img-fluid"
alt="Responsive Image">
<p>This image will scale to fit its column.</p>
</div>
<div class="col-md-6">
<img src="another-image.jpg" class="img-fluid rounded"
alt="Rounded Responsive Image">
<p>You can combine `img-fluid` with other image classes
like `rounded`.</p>
</div>
</div>
</div>
Other Image Classes:
o rounded: Adds border-radius to the image for rounded corners.
o rounded-circle: Makes the image completely circular (assuming it's square).
o img-thumbnail: Adds a slight border and padding, giving it a "thumbnail"
appearance.
2.8 Bootstrap Part 8: Nesting of Rows & Columns
You can "nest" Bootstrap grid systems within existing columns. This means you can place a
new row inside a col to create more complex layouts.
How it Works:
o When you place a row inside an existing col, that new row becomes a new 12-
column grid relative to its parent column.
o The sum of the column numbers in the nested row should add up to 12.
Example:
HTML
<div class="container">
<div class="row">
<div class="col-md-6">
<h2>Parent Column (Half Width on Medium+)</h2>
<p>This is content in the first main column.</p>
<div class="row">
<div class="col-6">
<h4>Nested Column 1 (Half of parent)</h4>
<p>Content within the nested grid.</p>
</div>
<div class="col-6">
<h4>Nested Column 2 (Half of parent)</h4>
<p>More nested content.</p>
9
</div>
</div>
</div> {# End of first col-md-6 #}
<div class="col-md-6">
<h2>Second Parent Column (Half Width on Medium+)</h2>
<p>This is content in the second main column.</p>
</div> {# End of second col-md-6 #}
</div> {# End of main row #}
</div> {# End of container #}
In this example, the col-md-6 divides the page in half. Inside that first col-md-6, a
new row is created. The col-6 inside that nested row will then take up half the width
of its parent col-md-6, which is effectively a quarter of the total page width.
10