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

unit 5 - Django Template Language.docx

This is notes of django template

Uploaded by

ayushkumar32388
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

unit 5 - Django Template Language.docx

This is notes of django template

Uploaded by

ayushkumar32388
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 21

Django Template Language (DTL)

Django's template system is one of its key features, designed to separate the logic of the
application (views) from its presentation (HTML). The Django Template Language (DTL)
provides tools for rendering dynamic web pages by combining static HTML and dynamic
content. DTL is a powerful templating system used in Django to dynamically generate
HTML. It separates the logic from the presentation, making your web applications more
maintainable and scalable. It allows developers to create dynamic web pages by embedding
variables, control structures, and other elements in HTML templates.
Key Features of DTL:
● Separation of Concerns: Template language helps to separate the presentation layer
from the business logic layer.
● Readable and Simple: DTL syntax is simple and easy to read, focusing on markup
rather than complex logic.
Key Components of Django Template Language:
1. Variables:
Variables are used to dynamically display data from the view in templates.
Syntax: {{ variable_name }}
Example: {{ user.username }} displays the username of the logged-in user.
2. Tags:
Tags are enclosed in {% %} and are used to perform logic operations such as loops,
conditionals, and template inclusions.
Common tags include:
{% if %}, {% for %}: Conditional and loop control structures.
{% include %}, {% extends %}: Template inheritance and inclusion.
{% block %}, {% endblock %}: Define content blocks for inheritance.
Example:
▪ {% if user.is_authenticated %}
▪ <p>Welcome back, {{ user.username }}!</p>
▪ {% endif %}
3. Filters:
Filters modify the value of a variable before displaying it in the template.
Syntax: {{ variable|filter_name }}
Common filters: date, length, lower, default, etc.
Example: {{ name|lower }} converts the name to lowercase.
4. Template Inheritance:
Allows for a common structure (like headers, footers) to be reused across multiple
templates, reducing redundancy.
The base template defines blocks (e.g., {% block content %}) that child templates can
override.
Example:
o Base template (base.html):
<html>
<head><title>{% block title %}My Site{% endblock
%}</title></head>
<body>{% block content %}{% endblock %}</body>
</html>
o Child template (home.html):
{% extends 'base.html' %}
{% block title %}Home Page{% endblock %}
{% block content %}
<h1>Welcome to the Home Page</h1>
{% endblock %}
5. Rendering Templates:
Templates are rendered in Django views using the render() function, which takes the
request, template name, and context (data to pass to the template).
Example:
from django.shortcuts import render
def home(request):
context = {'title': 'Welcome'}
return render(request, 'home.html', context)
6. Form Handling:
Django simplifies form creation and rendering. Form data is passed to templates using
context, and errors are automatically displayed if validation fails.
Example:
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

All Tags In Django Template Language


Django's Template Language (DTL) provides a variety of tags for controlling the structure
and logic of your templates. Below is a summary of the key tags available in Django
Template Language:
1. {% for %} - Loop Tag
The {% for %} tag is used to iterate over an iterable, such as a list, queryset, or dictionary,
and render content multiple times.
Syntax:
{% for item in items %}
<p>{{ item }}</p>
{% endfor %}
● Purpose: To iterate over a collection and repeat the enclosed HTML block for each
item in the collection.
● Example: Display a list of books, looping through each item and displaying the title.
2. {% if %} - Conditional Tag
The {% if %} tag is used for conditional logic. It renders a block of code only if a specific
condition is true.
Syntax:
{% if condition %}
<p>The condition is true!</p>
{% endif %}
● Purpose: To check conditions and render content based on whether the condition
evaluates to True.
● Example: Display a message if a user is logged in.
3. {% block %} - Block Tag
The {% block %} tag is used to define a block of content that can be overridden in child
templates. It is commonly used in base templates to define sections that can be replaced by
child templates.
Syntax:
{% block content %}
<p>Default content</p>
{% endblock %}
● Purpose: To define placeholder content that can be overridden in child templates. It
helps in template inheritance, enabling you to create a base template and extend it in
other templates.
● Example: Define a header or footer in a base template, which can be customized in
child templates.
4. {% include %} - Include Tag
The {% include %} tag is used to include another template file inside the current template. It
is useful for reusing common elements such as headers, footers, or sidebars.
Syntax:
{% include "header.html" %}
● Purpose: To include another template file at the location of the tag.
● Example: Reuse a navigation bar across multiple pages.
5. {% extends %} - Template Inheritance Tag
The {% extends %} tag is used in child templates to extend a parent template. It allows you to
create a basic structure in a base template and reuse it across multiple pages, replacing or
adding content in specific sections.
Syntax:
{% extends "base.html" %}
● Purpose: To inherit a parent template and override specific blocks using {% block
%}.
● Example: A child template extends a base template, overriding the content block.
6. {% csrf_token %} - CSRF Token Tag
The {% csrf_token %} tag is used to insert a CSRF (Cross-Site Request Forgery) token into
forms to protect them against CSRF attacks. Django uses CSRF tokens to verify that a
request comes from an authenticated and trusted source.
Syntax:
<form method="post">
{% csrf_token %}
<!-- Form fields go here -->
</form>
● Purpose: To insert a hidden input field containing a CSRF token that Django will
validate when the form is submitted.
● Example: Required for POST forms in Django to protect against CSRF attacks.
7. {% comment %} - Comment Tag
The {% comment %} tag is used to add comments in templates. These comments are not
rendered in the final HTML output and are ignored by the Django template engine.
Syntax:
{% comment %}
This is a comment
{% endcomment %}
● Purpose: To add comments in the template code for documentation or notes.
● Example: Place comments in templates for developers, explaining parts of the code.
8. {% load %} - Load Custom Template Tags and Filters
The {% load %} tag is used to load custom template tags or filters that are defined in Django
apps or libraries.
Syntax:
{% load custom_tags %}
● Purpose: To load custom tags or filters from a module so that they can be used in the
template.
● Example: Load a custom filter that formats dates in a specific way.
9. {% url %} - URL Tag
The {% url %} tag is used to reverse URL patterns by their name. This allows you to
dynamically generate URLs for views.
Syntax:
<a href="{% url 'book_detail' book.id %}">View Book</a>
● Purpose: To dynamically generate URLs based on URL patterns defined in urls.py.
● Example: Create links to view a specific book by referencing its URL name and
passing dynamic parameters like the book ID.
10. {% static %} - Static File Tag
The {% static %} tag is used to reference static files (like CSS, JavaScript, and image files) in
the templates. It ensures the correct URL is generated based on your STATIC_URL setting.
Syntax:
<img src="{% static 'images/logo.png' %}" alt="Logo">
● Purpose: To generate the correct URL for static files, ensuring they are served
correctly in different environments.
● Example: Link to a logo image or a CSS file located in the static directory.
11. {% with %} - Variable Assignment Tag
The {% with %} tag allows you to assign values to variables within a template. This can help
simplify complex expressions or avoid repetitive code.
Syntax:
{% with total_price=price|add:tax %}
<p>Total price: {{ total_price }}</p>
{% endwith %}
● Purpose: To assign temporary values to variables and use them within the template.
● Example: Calculate and display the total price with taxes included.
12. {% redirect %} - Redirect Tag (Django 3.1+)
The {% redirect %} tag allows you to redirect the user to a different URL, which is useful for
redirecting from one page to another within a template.
Syntax:
{% redirect 'home' %}
● Purpose: To redirect users to another page or view based on the URL name.
● Example: Redirect users to the homepage after submitting a form.

Example: Creating Template Objects


Creating Template Objects
In Django, templates are typically HTML files that are rendered dynamically by Django's
template engine. These templates are usually stored in the template’s directory of the Django
project.
Steps to create and use a template:
1. Create a template file in the templates directory, e.g., index.html.
2. Render the template in the view function, passing dynamic data as context.
Example:
1. HTML Template (index.html):
<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ header }}</h1>
<p>{{ content }}</p>
</body>
</html>
2. View (views.py):
from django.shortcuts import render
def home(request):
context = {
'title': 'Home Page',
'header': 'Welcome to Django!',
'content': 'This is a dynamic content area.',
}
return render(request, 'index.html', context)

Tags, Variables, and Filters


Tags: Tags are special syntax elements that control the logic and flow of your
template. Tags are a fundamental component of Django templates. They are enclosed
within
{% %} and allow for logic such as loops, conditionals, and inclusion of other
templates.
Types of Tags:
▪ Control Structures: {% if %}, {% for %}, {% else %}, {% endif %}
▪ Template Includes: {% include %}, {% extends %}, {% block %}
▪ Template Customization: {% load %}, {% static %}, {% url %}
Common tags include:
▪ if, elif, else: Conditional statements
▪ for: Looping over sequences
▪ include: Including other templates
▪ extends: Inheriting from base templates
Variables: Variables are placeholders for dynamic content. They are enclosed in
double curly braces {{ }}.

Example: <p>Today is {{ today_date }}</p>

Filters: Filters modify variables to produce different output. They are applied after
variables and are enclosed in pipe characters |. Common filters include:
o default: Provides a default value if the variable is empty
o date: Formats dates and times
o lower, upper: Converts text to lowercase or uppercase
o truncatechars: Truncates text to a specified number of characters
Example:
<p>The current date is {{ today_date|date:"Y-m-d" }}</p>
<p>{{ name|lower }}</p>

Rendering Templates
To render a template, Django’s render() function is used in views. This function takes three
arguments:
1. Request object: The HTTP request.
2. Template name: The HTML file to be rendered.
3. Context: A dictionary containing dynamic data to pass to the template.
Example:
from django.shortcuts import render

def home(request):
context = {'greeting': 'Hello, World!'}
return render(request, 'home.html', context)

Template Inheritance
Template inheritance allows you to create a base template with common elements (such as a
header, footer, or navigation bar) that can be reused across other templates. This helps avoid
redundancy and makes maintaining the application easier. Template inheritance allows you to
create reusable base templates and extend them to create more specific templates. Template
Inheritance in Django is a powerful feature that allows you to create a base template with
common structure and elements (like headers, footers, or navigation bars) and reuse it across
multiple templates. This reduces redundancy and makes your project more maintainable. In
Django, template inheritance works by using {% extends %} to inherit a base template and
{% block %} to define sections of the template that can be overridden by child templates.

● Base Template: Defines the overall layout and structure.


<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Django App{% endblock %}</title>
</head>
<body>
<header>
<h1>{% block header %}Welcome{% endblock %}</h1>
</header>
<div>
{% block content %}{% endblock %}
</div>
<footer>
<p>My footer content</p>
</footer>
</body>
</html>
● Child Template: Inherits from the base template and overrides or extends specific
blocks.

{% extends 'base.html' %}
{% block title %}Home Page{% endblock %}
{% block header %}Home Page Header{% endblock %}
{% block content %}
<p>Welcome to the home page!</p>
{% endblock %}

Form Handling
In Django, forms are used to capture and process user input. Django forms can be rendered
dynamically, and the form’s fields can be validated automatically. Django provides a
powerful form handling framework that simplifies the process of creating, validating, and
processing forms.

Example:
1. Form Class:
from django import forms

class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)
2. View:
from django.shortcuts import render
from .forms import ContactForm

def contact(request):
form = ContactForm()
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process form data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# Return a response (or redirect)
return render(request, 'contact.html', {'form': form})
3. Template (contact.html):
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>

Form Validation and Error Messages


In Django, forms are used to capture user input. Form validation ensures that the data entered
by the user is correct and meets the criteria defined by the application. Django provides
built-in tools for form validation and automatically handles error messages when the data is
invalid. Django provides automatic form validation. If the form does not pass validation,
error messages can be displayed next to the relevant form fields.

Key Concepts in Form Validation


1. Field Validation: Each form field has a set of built-in validators (like required,
max_length, min_value, etc.) to validate the data entered by the user. You can also
define custom validation logic using clean_fieldname() methods or the clean() method
for the entire form.
2. Error Messages: When the form data is invalid, Django automatically attaches error
messages to the form field. These messages are displayed to the user so they can
correct the issues.
3. Custom Validation: You can create custom validation logic by defining methods that
check the data according to your specific needs (e.g., checking if a username already
exists).

Steps to Handle Form Validation and Display Errors in Django


1. Creating the Form Class: In Django, forms are created as Python classes that inherit
from forms.Form or forms.ModelForm.
2. Form Field Validation:
o Django's form fields come with some built-in validation. For example,
CharField requires the input to be a string, EmailField validates if the input is
a valid email, and so on.
o You can define custom validation by creating a method called
clean_<field_name>() or by overriding the clean() method for more complex
validation.
3. Displaying Error Messages: Once validation fails, error messages are attached to the
form fields. You can display these messages in the template.

Example of Form Validation and Error Messages in Django


Step 1: Create the Form Class
In your Django project, start by creating a form class. For example, we will create a contact
form that takes a user's name, email, and message.

# forms.py
from django import forms
from django.core.exceptions import ValidationError

class ContactForm(forms.Form):
name = forms.CharField(max_length=100, required=True, label='Your Name')
email = forms.EmailField(required=True, label='Your Email')
message = forms.CharField(widget=forms.Textarea, required=True, label='Your Message')

# Custom validation for the name field


def clean_name(self):
name = self.cleaned_data.get('name')
if 'admin' in name.lower():
raise ValidationError('Name cannot contain the word "admin"')
return name

# Custom validation for email field


def clean_email(self):
email = self.cleaned_data.get('email')
if '@example.com' in email:
raise ValidationError('We do not accept emails from "example.com"')
return email

# Custom form-level validation (for checking if the message is too short)


def clean(self):
cleaned_data = super().clean()
message = cleaned_data.get('message')
if len(message) < 10:
self.add_error('message', 'Message must be at least 10 characters long.')
return cleaned_data
Explanation of the Form:
● Field Definitions: We define three fields: name, email, and message. Each of these
fields is required, and their types are validated automatically (e.g., EmailField ensures
the input is a valid email).
● clean_name(): This is a custom validation method for the name field. It checks if the
name contains the word "admin" (case-insensitive), and raises a ValidationError if it
does.
● clean_email(): This custom method checks if the email contains "@example.com". If
it does, a validation error is raised.
● clean(): This method performs form-level validation. It checks the length of the
message field and ensures it is at least 10 characters long.

Step 2: Handle Form in Views


Next, in the views.py, handle the form submission and validation.
# views.py
from django.shortcuts import render
from .forms import ContactForm

def contact_view(request):
if request.method == 'POST':
form = ContactForm(request.POST)
if form.is_valid():
# Process the data
name = form.cleaned_data['name']
email = form.cleaned_data['email']
message = form.cleaned_data['message']
# In a real scenario, you would save this to the database or send an email
return render(request, 'contact_success.html', {'name': name})
else:
# If the form is invalid, it will contain errors
return render(request, 'contact_form.html', {'form': form})
else:
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})

Explanation of the View:


● POST Method: If the form is submitted, we create a ContactForm instance with the
POST data and check if it is valid with form.is_valid().
● If Form is Valid: If the form passes validation, we can process the data (e.g., save it
to a database or send an email).
● If Form is Invalid: If validation fails, Django will automatically attach error
messages to the form fields. These errors are then passed back to the template, where
they can be displayed.

Step 3: Display the Form and Errors in Templates


The template contact_form.html will render the form and show any error messages.
<!-- contact_form.html -->
<form method="POST">
{% csrf_token %}
{{ form.as_p }} <!-- Renders the form fields with error messages if any -->
<button type="submit">Submit</button>
</form>

{% if form.errors %}
<ul>
{% for field, errors in form.errors.items %}
<li>{{ field }}:
<ul>
{% for error in errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
</li>
{% endfor %}
</ul>
{% endif %}
Explanation of Template:
● {{ form.as_p }}: This renders the form fields as paragraphs. Django automatically
displays error messages next to the corresponding fields when they are invalid.
● Displaying Errors: If there are any errors (form.errors), they are displayed in an
unordered list. Each field's errors are listed under the field name

Form Display
To display a form in the template, you can use Django’s built-in methods like {{ form.as_p
}}, {{ form.as_table }}, or {{ form.as_ul }}. Each of these methods renders the form fields in
different formats. Django's form rendering system generates HTML forms based on the form
fields defined in your form class. You can customize the appearance of forms using template
tags and filters.

Steps to Display a Form:


1. Create a Form Class:
o Define the structure of your form using Django's form fields.
o Each field specifies the type of input, validation rules, and additional
attributes.
from django import forms

class ContactForm(forms.Form):
name = forms.CharField(max_length=100)
email = forms.EmailField()
message = forms.CharField(widget=forms.Textarea)

2. Render the Form in a View:


o Instantiate the form object in your view.
o Pass the form instance to the template.
from django.shortcuts import render

def contact_view(request):
form = ContactForm()
return render(request, 'contact_form.html', {'form': form})

3. Display the Form in the Template:


o Use the as_p method to render the form as a series of <p> tags, each
containing a label and input field.
HTML
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
Customizing Form Display:
● Customizing Field Appearance:
o Use CSS to style the form and its elements.
o You can also customize the HTML output using template tags and filters.
● Adding Error Messages:
o Django automatically displays error messages for invalid form submissions.
o You can customize the appearance of error messages using CSS.
● Using Different Rendering Methods:
o as_table: Renders the form as an HTML table.
o as_ul: Renders the form as an unordered list.
o as_hidden: Renders hidden fields.
● Customizing Field Labels and Placeholders:
o Set label and placeholder attributes for each field in the form class.

Example with Customization:


HTML
<form method="post">
{% csrf_token %}
<div class="form-group">
{{ form.name.label_tag }}
{{ form.name }}
{% if form.name.errors %}
<div class="errorlist">
{% for error in form.name.errors %}
<p>{{ error }}</p>
{% endfor %}
</div>
{% endif %}
</div>
<button type="submit">Submit</button>
</form>

To develop a webpage explaining Django CRUD (Create, Read, Update, Delete) functions
using Class-Based Views (CBVs), we'll walk through the process of setting up a simple
Django app with class-based views for each of the CRUD operations.
Step-by-Step Guide
1. Create a New Django Project and App
First, make sure you have Django installed. If you don’t, you can install it using pip:
pip install django
Now, create a new Django project and an app where we'll build our CRUD functionality.
# Create a new project
django-admin startproject crud_project

# Navigate to the project directory


cd crud_project

# Create a new app


python manage.py startapp crud_app
2. Set Up the Models
In crud_app/models.py, define a simple model to represent an entity. Let's create a model
called Book for managing book data.
crud_app/models.py

from django.db import models

class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=100)
published_date = models.DateField()

def __str__(self):
return self.title
After defining the model, run the migrations to create the database schema:
# Create migration files
python manage.py makemigrations

# Apply migrations to the database


python manage.py migrate
3. Create Views Using Class-Based Views (CBVs)
In Django, CRUD operations can be performed using class-based views. These views offer
built-in functionality for handling common operations.
crud_app/views.py
In views.py, we will use Django's generic class-based views for each CRUD operation.
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import ListView, DetailView, CreateView, UpdateView,
DeleteView
from .models import Book
# Create View - Add a new book
class BookCreateView(CreateView):
model = Book
template_name = 'book_form.html'
fields = ['title', 'author', 'published_date']
success_url = '/books/'

# Read View - List all books


class BookListView(ListView):
model = Book
template_name = 'book_list.html'
context_object_name = 'books'

# Read View - Detail of a single book


class BookDetailView(DetailView):
model = Book
template_name = 'book_detail.html'
context_object_name = 'book'

# Update View - Edit a book


class BookUpdateView(UpdateView):
model = Book
template_name = 'book_form.html'
fields = ['title', 'author', 'published_date']
success_url = '/books/'

# Delete View - Delete a book


class BookDeleteView(DeleteView):
model = Book
template_name = 'book_confirm_delete.html'
success_url = '/books/'

Here is what each class does:


● BookCreateView: Handles the form to create a new Book.
● BookListView: Displays a list of all books.
● BookDetailView: Displays the details of a specific book.
● BookUpdateView: Provides a form to update an existing book.
● BookDeleteView: Confirms and deletes a book.

4. Set Up URLs
In crud_app/urls.py, create URL patterns that map to the views we created.
crud_app/urls.py
from django.urls import path
from .views import BookListView, BookDetailView, BookCreateView,
BookUpdateView, BookDeleteView

urlpatterns = [
path('books/', BookListView.as_view(), name='book_list'),
path('book/<int:pk>/', BookDetailView.as_view(), name='book_detail'),
path('book/new/', BookCreateView.as_view(), name='book_create'),
path('book/<int:pk>/edit/', BookUpdateView.as_view(), name='book_edit'),
path('book/<int:pk>/delete/', BookDeleteView.as_view(), name='book_delete'),
]

5. Include the App URLs in the Main urls.py


In crud_project/urls.py, include the crud_app.urls to make the app's URLs accessible in the
project.
crud_project/urls.py
from django.contrib import admin
from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('', include('crud_app.urls')), # Include the URLs from the CRUD app
]
6. Create Templates
Now, let’s create HTML templates for the views. All templates will be stored in the templates
folder of crud_app.
crud_app/templates/book_list.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Books</title>
</head>
<body>
<h1>Book List</h1>
<a href="{% url 'book_create' %}">Add a new book</a>
<ul>
{% for book in books %}
<li>
<a href="{% url 'book_detail' book.pk %}">{{ book.title }}</a>
<a href="{% url 'book_edit' book.pk %}">Edit</a>
<a href="{% url 'book_delete' book.pk %}">Delete</a>
</li>
{% endfor %}
</ul>
</body>
</html>

crud_app/templates/book_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ book.title }}</title>
</head>
<body>
<h1>{{ book.title }}</h1>
<p>Author: {{ book.author }}</p>
<p>Published Date: {{ book.published_date }}</p>
<a href="{% url 'book_edit' book.pk %}">Edit</a>
<a href="{% url 'book_delete' book.pk %}">Delete</a>
<a href="{% url 'book_list' %}">Back to Book List</a>
</body>
</html>

crud_app/templates/book_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ view.title }}</title>
</head>
<body>
<h1>{{ view.title }}</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
<a href="{% url 'book_list' %}">Back to Book List</a>
</body>
</html>

crud_app/templates/book_confirm_delete.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Confirm Delete</title>
</head>
<body>
<h1>Are you sure you want to delete this book?</h1>
<p>{{ book.title }} by {{ book.author }}</p>
<form method="post">
{% csrf_token %}
<button type="submit">Yes, delete it</button>
</form>
<a href="{% url 'book_list' %}">Cancel</a>
</body>
</html>
7. Admin Panel (Optional)
To easily add, update, or delete books, you can register the Book model in the Django
admin.
crud_app/admin.py

from django.contrib import admin


from .models import Book

admin.site.register(Book)
8. Run the Server
Now that everything is set up, you can run the server:
python manage.py runserver
9. Visit the Web Pages
● Create a Book: Visit /book/new/ to add a new book.
● List Books: Visit /books/ to view the list of books.
● View Book Details: Click on a book title in the list to view its details.
● Edit Book: Click on the "Edit" link next to a book to update it.
● Delete Book: Click on the "Delete" link next to a book to delete it.

Explain about get and post method in HTML


The GET and POST methods are the two most commonly used HTTP request methods in
HTML forms. They define how data is sent from the client (browser) to the server when a
form is submitted. Each method has specific use cases, characteristics, and security
implications. Here’s a detailed explanation:
1. GET Method
The GET method is used to send data to the server by appending it to the URL. It is typically
used for retrieving data without causing any side effects (such as data modification) on the
server.
Characteristics:
● Data in URL: The data is appended to the URL as query parameters. This means the
data is visible in the browser's address bar.
● Limited Data Size: Since the data is part of the URL, the amount of data you can
send is limited (the URL has a length limit, typically around 2048 characters).
● Bookmarkable and Shareable: Since the data is part of the URL, GET requests can
be bookmarked or shared. The same data will be included in the URL.
● Less Secure: Data sent using GET is visible in the URL, so it is not secure for
sending sensitive information (like passwords or credit card numbers).
● Idempotent: GET requests are considered "safe" and "idempotent", meaning they
should not change the state of the server. They are typically used to fetch data from
the server without causing any side effects (e.g., viewing a webpage or searching).
Example:
html
<form method="get" action="/search/">
<label for="query">Search:</label>
<input type="text" id="query" name="query">
<button type="submit">Search</button>
</form>
● In this case, when the form is submitted, the data (the search query) will be sent in the
URL like this:
bash
Copy code
/search/?query=example
2. POST Method
The POST method is used to send data to the server for processing (e.g., saving data to a
database, updating records, etc.). Unlike GET, the data sent using POST is included in the
body of the HTTP request, not in the URL.
Characteristics:
● Data in Body: The data is sent in the body of the HTTP request, not as part of the
URL. This makes it more secure compared to GET because sensitive information
(like passwords) is not visible in the browser’s address bar.
● No Size Limit: POST requests do not have the same size limitations as GET requests,
so you can send much larger amounts of data.
● Not Bookmarkable: Since the data is sent in the body and not part of the URL, POST
requests are not bookmarkable or shareable in the same way as GET requests.
● More Secure: While still not fully secure (since the data can be intercepted without
encryption), POST is more secure than GET when transmitted over HTTPS because
the data is not exposed in the URL.
● Non-idempotent: POST requests are typically used to create, update, or modify data
on the server, which can change the state of the server. This means POST requests are
not idempotent, and repeated POST requests may have side effects (e.g., creating
multiple records).
Example:
html
Copy code
<form method="post" action="/submit/">
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<button type="submit">Submit</button>
</form>
● In this case, when the form is submitted, the data will be sent in the body of the HTTP
request, not in the URL.
● The data sent would be something like:
makefile
Copy code
username=example&password=secret
Key Differences Between GET and POST Methods
Feature GET POST
Data Data is appended to the URL
Data is sent in the body of the request
Location as query strings
Visibility Data is visible in the URL Data is not visible in the URL
Limited (due to URL length
Data Size No size limit (limited by server config)
restrictions)
Less secure (data visible in More secure (data not in URL, but still needs
Security
URL) HTTPS for full security)
Can be cached and
Caching Cannot be cached or bookmarked
bookmarked
Retrieving data, such as
Use Case Submitting sensitive data or modifying data
searches or queries
Idempotent (should not change
Idempotence Non-idempotent (can change server state)
server state)
When to Use GET vs POST
● GET should be used when:
o Retrieving data or displaying information.
o The operation does not modify data on the server (e.g., search queries).
o The request can be safely cached and bookmarked.
● POST should be used when:
o Sending sensitive data (e.g., login forms, registration forms).
o Modifying or creating data on the server (e.g., submitting a form to add a new
record).
o The request contains large amounts of data (e.g., file uploads).
Conclusion
● GET is suitable for retrieving data without side effects, and it exposes data in the
URL (which has security limitations).
● POST is used when you need to send data securely and modify data on the server,
making it suitable for operations like form submissions, data updates, and file
uploads.
For secure, sensitive, and large data submissions, POST is generally preferred, while GET is
used for non-sensitive data retrieval.

You might also like