0% found this document useful (0 votes)
15 views95 pages

Getting Started

Django is a high-level Python web framework that simplifies the creation of secure and maintainable websites, featuring an ORM, admin interface, and built-in security measures. It follows the MTV (Model-Template-View) architectural pattern, promoting organized code and reusability through principles like DRY (Don't Repeat Yourself) and Convention Over Configuration. Key features include portability, speed, security, scalability, and an extensive community, making it suitable for various web applications.

Uploaded by

parthivajith40
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)
15 views95 pages

Getting Started

Django is a high-level Python web framework that simplifies the creation of secure and maintainable websites, featuring an ORM, admin interface, and built-in security measures. It follows the MTV (Model-Template-View) architectural pattern, promoting organized code and reusability through principles like DRY (Don't Repeat Yourself) and Convention Over Configuration. Key features include portability, speed, security, scalability, and an extensive community, making it suitable for various web applications.

Uploaded by

parthivajith40
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

Django is a high-level Python web framework designed to make it easier and faster

to create secure and maintainable websites.


Django provides ready-to-use features like a login system, database connections
with an Object-Relational Mapper (ORM), CRUD operations, and a dynamic
administrative interface. It is especially useful for database-driven websites and
supports multiple database backends such as PostgreSQL, MySQL, SQLite, and
others. The framework also includes extensive built-in security features and
scalability options. Django was created in 2003 and is maintained by the Django
Software Foundation.

django mtv model template view:

The MTV (Model-Template-View) pattern is the architectural structure used by


Django to organize web application code and workflow. It separates the application
into three main components:

Model
The Model acts as the data layer of the application. It defines the structure of the
database, manages data, and handles all data-related logic, including querying,
inserting, updating, and deleting records. Models are usually Python classes that
map directly to tables in the database.geeksforgeeks+3

Template
The Template serves as the presentation layer, responsible for rendering HTML and
presenting data to the user. Templates are usually HTML files that can include
Django Template Language (DTL) tags to inject dynamic data and logic for how that
data is displayed on the client side.dev+3

View
The View is the business logic layer. It receives user requests, interacts with the
Model to process data, and then selects the appropriate Template to present
information. In Django, views are Python functions or classes that return HTTP
responses, which often render templates populated with data.freecodecamp+4

This separation helps keep the code organized and maintainable, making it easier to
develop dynamic, database-driven web applications in Django.

Data - Model
Layout - Template
Logic - View
python manage.py startapp app_name – for creating new django app

Django Philosophy and Your First App


Django's Core Philosophy
Django was built around several fundamental principles that guide its design and
development approach. Understanding these principles will help you write better
Django applications.

Don't Repeat Yourself (DRY)


Django emphasizes eliminating code duplication by extracting common patterns into
reusable components. This principle encourages you to write code once and use it
everywhere, making maintenance easier and reducing bugs.

Convention Over Configuration


Django provides sensible defaults and follows established patterns, so you spend
less time configuring and more time building. The framework makes assumptions
about how you want to structure your application, reducing decision fatigue.

Explicit is Better Than Implicit


Following Python's philosophy, Django favors clear, readable code over "magic" that
hides complexity. This makes debugging easier and code more maintainable.

Loose Coupling and High Cohesion


Django apps should be independent modules that can work together seamlessly.
Each component should have a single, well-defined purpose while being able to
interact with other components.

"Batteries Included"
Django comes with a comprehensive set of built-in features including an ORM, admin
interface, authentication system, URL routing, templating engine, and more. This
reduces the need for third-party packages for common functionality.

Key Features Of Django

1. Portable

Since Django is a Python-based web framework it runs on


almost all platforms. Almost all Linux flavors, Windows
Editions, and Mac Versions support Django. Django is also
officially supported by many web-hosting server platforms
that even provide detailed documentation on hosting Django
Applications on their servers.

2. Speed

Frameworks are usually developed to make the application


development process easier and faster without having to
write code from scratch to even simple things.
Django acts as a Catalyst while Developing Web Applications
compared to other backend frameworks. Django provides
Comfort and makes the development of complex and data-
driven websites much easier.

3. Security

Django developers made security a priority while developing


the language. Django has inbuilt standard encryption
packages required to secure the website. The framework
architecture defends common security issues like
Clickjacking, SQL vulnerabilities, and cross-site scripting.
With a wide range of open source communities, Django
usually comes first in fixing security vulnerabilities and
alerts other frameworks.

Django’s application source code doesn’t show up in web


browser source code and offers various other features like
scanning uploaded content and access control security.
Django is a versatile framework for the robust security it
offers.

4. Batteries-included

Batteries-included literally means that Django has


everything a developer needs to develop a web application.
Here batteries refers to libraries and tools required for
common use cases. Admin Interface, Session Management,
Sitemaps, Authentication Packages, Django ORM, HTTP
Libraries are “batteries”, simply because no other
framework offers these tools that make the web
development process easy-to-build.
5. Open Source and Huge Community

Django is an Open Source Framework, the GitHub


Repository of Django receives more than 2000 contributions
every month. Due to its wide adaptiveness among the
technology industry and its open-source nature, updates are
frequently released thus it’s a continuously evolving
framework.

Beginners and programmers struck with a problem can


easily find solutions due to its active community on the
Internet.

6. SEO Friendly

Most of the Python source code is Human Readable, which


makes it an SEO-Friendly framework. Sitemaps built-in with
Django make it easier for developers to be unaware of
Search Engine Optimization and yet enjoy its benefits.
Django lets you generate SEO-optimized URLs, it also
provides various libraries to optimize the meta description of
the webpage which will be used by search engines to rank
the Website.

7. Scalability

Django can handle large amounts of traffic and provide API


Usage to around 450+ million users. It is widely used among
top technology industries like Dropbox which is a cloud
technology for storing and sharing files.
Django makes applications scalable by providing the ability
to plug and unplug default components. Developers can even
extend their application by adding plugins seamlessly in a
production application.

8. Thoroughly Tested

Frameworks usually have a low user base and aren’t


adopted by a large community, unlike Programming
Languages. There are a lot of frameworks for Web
Development, but Django happens to be the most adopted
framework. Therefore, it is continuously tested and
improved by a large developer audience.

9. Superior Framework Documentation

When it comes to languages and frameworks, they evolve on


a regular basis. It is also hard to find a textbook for a
framework since publishers can’t release new editions
regularly.

Having good documentation solves this issue especially


when you’re learning a new framework. It is hard to find
good documentation for framework technologies.

But it isn’t the case with Django. Django has great


documentation and obeys Open Source Technology
Documentation Standards. They even have topic guides,
reference, and how-to guides to guide developers in solving
key problems on their official website. If you run into any
issue while programming, you can simply go through the
documentation and resolve the issue.

10. Versatile

Typically frameworks are only used by the publishing


industry on the Internet. Django is by far the most versatile
framework. Developers can build almost anything, ranging
from social networks to financial platforms. In fact, the
framework name “Django” literally means – multifaceted
nature.

11. DRY Principle

DRY is the Opposite principle of WET : We Edit Too Much.

When developing a web application, there is a lot of


repetition involved such as working with HTML templates
and business logic. Duplication also leads to maintenance
issues and logical contradictions .

Django follows Don’t Repeat Yourself Philosophy, which


forces developers to not have to write the code repeatedly.
12. Django’s ORM

ORM stands for Object Relational Mapper. Django’s ORM


enables you to interact with databases in a convenient
manner. Developers need not to learn SQL to manage their
database and can entirely depend on Django’s ORM to
handle even the complex things in the simplest possible
manner.

13. Free Flow Coding

Django does not import any packages unlike any other


framework. It is a complete package and does not ask for
any imports and third party libraries. It doesn’t allow bad
code or unwanted functions by default therefore developers
avoid application bugs before it goes live to the production
environment.

14. Multilingual Support

Django supports its websites according to the audience’s


preferred language and formats. This feature allows
developers to specify parts of the application required for
translation, thus making your application reach a wide range
of audience without having to develop separate sites for
each language .

15. Admin Interface

Django’s Admin Interface can be a lifesaver for a lot of tasks.


You can manage your databases, provide access controls to
other users. Graphical User Interface can perform all the
required CRUD(Create,Read,Update,Delete) methods
without having to rely on commands. The Default Admin
Interface could save a lot of time for developers who need an
Admin Interface .

16.Packages

Django is a full-stack web development framework kit as it


offers various packages to build a fully functional
application. It restricts the developers from relying on extra
technologies by providing packages for almost everything.

■ Django-rest-framework to create APIs with Django .


■ Django-cors-headers package to create cross-origin
site response requests .
■ Django-debug-toolbar to help developers debug
Django Apps .
■ Django-allauth to allow local and social
authentication .
There are many packages available, Django Developers need
to simply use these packages according to their use case.

in

in Django one Project has multiple apps when we creating the project that time the
same app also created django
1. manage.py
If you are not new to Django, you must have seen the word “command-line
utility” many times. But what does this mean?

Well, by using the command-line utility, you can migrate i.e., either import
or export metadata objects across different domains or setup. You can
create one or more objects within an object or its multiple objects.

Now straight away coming to the topic. What is manage.py?

This file is used as a command-line utility for our projects. We will use this
file for debugging, deploying, and running our web applications.

The file contains the code for running the server, makemigrations or
migrations, and several other commands as well, which we perform in the
code editor.

It performs the same things as django-admin but also provides some


project-specific functionality.
There are several commands under manage.py. Few important ones are
as follows:

1. manage.py
If you are not new to Django, you must have seen the word “command-line
utility” many times. But what does this mean?

Well, by using the command-line utility, you can migrate i.e., either import
or export metadata objects across different domains or setup. You can
create one or more objects within an object or its multiple objects.

Now straight away coming to the topic. What is manage.py?

This file is used as a command-line utility for our projects. We will use this
file for debugging, deploying, and running our web applications.

The file contains the code for running the server, makemigrations or
migrations, and several other commands as well, which we perform in the
code editor.

It performs the same things as django-admin but also provides some


project-specific functionality.

There are several commands under manage.py. Few important ones are
as follows:

● runserver: Starts the development serverdjangoproject+1


● makemigrations: Creates database migration files based on model
changesdjangoproject
● migrate: Applies database migrationsdjangoproject
● createsuperuser: Creates admin user accountdjangoproject
● collectstatic: Collects static files for productiondjangoproject
● test: Runs project testsdjangoproject
● shell: Opens Django interactive shell
● manage.py: This small but mighty script serves as

the gateway to various Django management

commands. It’s the tool through which you initiate

the development server, create applications, run

migrations, and more. manage.py is the conductor's

baton, guiding your project's activities.

● my_project/settings.py: As the name suggests, this

file houses the settings that configure your Django

project. From database configurations to

middleware lists, this is where you define how your

application functions. It’s akin to the blueprint that

shapes the structure of your project’s behavior.

● my_project/urls.py: The URL dispatcher — encoded

within urls.py—maps URLs to views. This file

determines which view is displayed when a specific

URL is accessed. It's like a roadmap that navigates

users through the intricacies of your application's

pages.
● my_project/wsgi.py: Short for Web Server Gateway

Interface, wsgi.py serves as the entry point for your

application when deployed on a production server.

It's the bridge connecting your application to the

web server, enabling it to handle incoming

requests.

● my_project/asgi.py: Similar to wsgi.py, asgi.py is the

entry point for asynchronous web servers. It

stands for Asynchronous Server Gateway Interface

and facilitates the handling of asynchronous HTTP

requests.

● my_project/__init__.py: This seemingly unassuming

file holds the magic that transforms a directory

into a Python package. It’s essential for organizing

and importing modules across your project


1. models.py: At the heart of every application lies

the models.py file. This is where you define the data

structures using Django's ORM (Object-Relational

Mapping). Each model class represents a table in

the database. This file forms the foundation of your

application's data management.

2. views.py: The views.py file encapsulates the logic

that defines how your application interacts with

users' requests. Views handle data processing,

rendering templates, and responding to actions.

This file transforms user interactions into tangible

responses.

3. tests.py: Test-driven development gains

momentum through the tests.py file. Here, you

write unit tests to ensure your application's

components function as expected. These tests

bolster the reliability and stability of your

codebase.
4. admin.py: The admin.py file isn't just for

administrators—it configures how your

application's models are presented in Django's

admin interface. This file allows administrators to

manage data seamlessly.

5. migrations: This directory is a blueprint of all

changes in your application models.

6. Other Files: Additional files might surface based

on your application’s needs. For instance, forms.py

houses form classes for data input, urls.py maps

URLs to views, and apps.py manages application-

specific configurations.

Naming Conventions

Consistency in naming conventions enhances code

readability. Follow these conventions:


● Apps: Use lowercase names, with underscores

instead of spaces. Example: my_app.

● Modules: Use lowercase names with underscores

for module files. Example: my_module.py.

● Classes: Use CamelCase for class names. Example:

MyClass.

● Functions and Variables: Use lowercase with

underscores for function and variable names.

Example: my_function

Modular Code Design

Organize your codebase into modular components, making

each component focused on a specific task. This makes

code easier to understand, test, and maintain.

● Apps: Divide your project into multiple apps based

on functionality. Each app should be self-

contained, handling a specific feature.


● Views: Keep your views concise and focused on

handling HTTP requests. Use class-based views for

better organization.

● Models: Organize models in a way that reflects

your project’s data structure. Utilize model

inheritance and related fields.

● Templates: Use template inheritance to avoid code

duplication. Create reusable templates and keep

them organized.

● Utils: For utility functions or classes that are used

across the project, create a utils module within

your app.

from django.http import


HttpResponse,HttpResponseNotfound

def printre(request,a,b):

return HttpResponse(f"result = {a+b}")

from django.shotcuts import render


return (request,’index.hmtl’,{‘status’:200,}

Url Pattern

Understanding Django URL Patterns and the path


Function

In Django, URL patterns are a core part of routing — they


connect requested URLs to the appropriate Python views
that handle those requests. These patterns are typically
defined in the urls.py file of your project or app.

What is urlpatterns?

urlpatterns is a list in urls.py that holds URL pattern


objects. Django checks these patterns in order, and when
it finds one matching the requested URL, it calls the linked
view.

What is the path function?

path() is a convenient helper function introduced in


Django 2.0 to define URL patterns clearly and simply. It
takes at least two arguments:

route: a string describing the URL pattern (e.g.,


'articles/<int:id>/')
view: the view function or class that handles the matched
URL

It optionally takes kwargs and a name.

Example snippet:

python

from django.urls import path

from . import views

urlpatterns = [

path('articles/<int:id>/', views.article_detail,
name='article_detail'),

This pattern matches URLs like /articles/5/ and passes


id=5 to the article_detail view.

Where does path come from?

It is imported from Django's URL dispatcher module:


python

from django.urls import path

Other functions similar to path include:

re_path(): which allows defining URL patterns using


regular expressions (more flexible but complex).

include(): which lets you include other URL configuration


modules, useful for modular apps.

path()

path() is the simple, recommended helper for most URL


patterns and supports converters to capture URL parts as
typed parameters.

Signature (conceptual): path(route, view, kwargs=None,


name=None).

Route examples:

'' or '' — root of the current URLconf.


'posts/int:id/' — captures an integer and passes id to the
view.

'users/slug:username/' — captures a slug and passes


username.

Typical import: from django.urls import path.

Example usage:

from django.urls import path

from . import views

urlpatterns = [

path('', views.index, name='home'),

path('posts/int:id/', views.post_detail, name='post_detail'),

What happens at runtime: Django tests patterns in order;


when a pattern matches, Django calls the view with
request plus any captured parameters (converted to
Python types when converter used).

re_path()
re_path() uses regular expressions for patterns and is
useful when path() converters are not flexible enough.

Signature (conceptual): re_path(regex, view,


kwargs=None, name=None).

Typical import: from django.urls import re_path.

Example usage:

from django.urls import re_path

urlpatterns = [

re_path(r'^articles/(?P<year>[0-9]{4})/$',
views.archive_by_year, name='archive_year'),

Notes:

Captured groups are passed as strings (unless post-


processed).

Use raw-string literals (r'...') to avoid backslash escaping


issues.
Keep readability in mind — prefer re_path only when path
converters cannot express the requirement.

include()

include() lets a URLconf include another URLconf —


essential for modular apps and for keeping project-level
urls.py small.

Typical import: from django.urls import include, path.

How it’s used:

In project-level urls.py:

urlpatterns = [

path('blog/', include('blog.urls')),

path('api/', include('api.urls')),

The included module (e.g., blog/urls.py) defines its own


urlpatterns; the prefix from the including pattern is
prepended to matches.
Benefits:

Decouples apps (each app manages its own routes).

Makes large projects maintainable.

Enables namespacing (see below).

Namespaces and named routes

● name argument in path/re_path assigns a name for reverse URL lookup.


● include supports app_name and namespaces for isolating named routes:
● In app urls.py set app_name = 'blog' and define named patterns; then
include with namespace: path('blog/', include('blog.urls',
namespace='blog')).
● Use reverse() or the {% url %} template tag to build URLs by name instead of
hardcoding.

Examples together
● Project-level urls.py:
● from django.urls import path, include
urlpatterns = [
path('', include('main.urls')),
path('blog/', include('blog.urls')),
path('admin/', admin.site.urls),
]
● App-level blog/urls.py:
● from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.index, name='index'),
path('post/
● int:id
● /', views.post_detail, name='post_detail'),
re_path(r'^archive/(?P<year>[0-9]{4})/$', views.archive, name='archive'),
]

Imagine you have a blog website where each article has a URL. Instead of using a
plain number like /articles/123/, you'd want a more human-readable URL, such as
/articles/building-a-django-site/. Here, the 'building-a-django-site' part
is a slug.

A slug is a URL-friendly string made of lowercase letters, numbers, hyphens, and


underscores. It often represents the title of the content in a clean way. For example:
● Title: "How to Build a Django Site"
● Slug: "how-to-build-a-django-site"
When a user visits /articles/how-to-build-a-django-site/, Django can extract
the 'how-to-build-a-django-site' part and use it to find the correct article in your
database.
SecurityMiddleware
Adds security-related headers to HTTP responses (like X-XSS-Protection and X-
Content-Type-Options), enforces SSL/TLS redirects, and strengthens overall site
security by providing several enhancements to the request/response cycle.

SessionMiddleware
Enables session management across requests. This middleware allows Django to
store and retrieve per-user session data (like login status or a shopping cart) using
cookies and server-side storage.

CommonMiddleware
Handles common operations such as URL redirection (e.g., ensuring trailing
slashes), sending 404 errors for missing favicon requests, and standardizing URLs.
Useful for URL normalization and basic request handling.

CsrfViewMiddleware
Protects against Cross-Site Request Forgery attacks. It injects and verifies a CSRF
token in POST requests to ensure forms are submitted from trusted sources.

AuthenticationMiddleware
Associates users with each request using Django’s authentication framework,
making the logged-in user available through request.user in views. Depends on the
session framework to keep track of user authentication state.

MessageMiddleware
Enables temporary message storage, such as notifications or status messages,
which can be displayed to users after actions like form submission. Works alongside
Django’s messages framework.

XFrameOptionsMiddleware
Provides clickjacking protection by setting the X-Frame-Options header, which tells
browsers whether a page can be displayed within a <frame>, <iframe>, or <object>,
typically preventing other sites from embedding your content in a hidden way.
{% load static %}

{% url 'home_page' as home %}

<link rel="stylesheet" href="{% static 'css/style.css'


%}" />

<form class="right" action="{{home}}"> this redirect to


home_page name url
In Django Template Language (DTL), a tag is a special instruction or logic statement
enclosed in {% ... %} that tells Django to perform some action — like displaying
data, looping, or applying conditions — when rendering the template.

🧩 Basic Syntax
{% tag_name parameters %}

Tags are always wrapped inside {% %} (unlike variables, which use {{ }}).
🧠 Common Types of Tags
Type Example Description

Output {% if condition %} ... {% Used for conditional logic


control endif %}

Looping {% for item in list Used to iterate over a list or


%} ... {% endfor %} queryset

Extending {% extends 'base.html' %} Used for template inheritance


templates

Blocks {% block content %} ... Define sections that can be


{% endblock %} overridden in child templates

Including {% include 'header.html' Inserts another template’s


%} content

Static files {% load static %} → <img Used to load and use static
src="{% static files
'images/logo.png' %}">

Comments {% comment %} This won't Used for adding comments


be shown {% endcomment %} inside templates

Custom tags {% my_custom_tag %} You can create your own tags


in a custom templatetags
Python module

⚡ Example
{% if user.is_authenticated %}
<p>Welcome, {{ user.username }}!</p>
{% else %}
<p>Please log in.</p>
{% endif %}

Here:

● {% if %} and {% endif %} are tags

● {{ user.username }} is a variable
✅ Summary

● Tags = logic and control flow ({% ... %})

● Variables = data display ({{ ... }})

● Filters = modify variables ({{ name|upper }})

In Django Template Language (DTL), a filter is a way to modify or format the value of
a variable before displaying it in the template. Filters are applied using the pipe
symbol |.

🧩 Basic Syntax
{{ variable|filter_name }}

You can also chain multiple filters:

{{ variable|filter1|filter2 }}

🧠 Common Built-in Filters


Filter Example Description
date `{{ today date:"D M Y" }}`
lower `{{ name lower }}`
upper `{{ name upper }}`
title `{{ name title }}`
length `{{ mylist length }}`
default `{{ value default:"N/A" }}`
truncatechars `{{ texttruncatechars:10 }}`
safe `{{ html_content safe }}`
add `{{ num add:5 }}`
date `{{ mydate date:"Y-m-d" }}`
⚡ Example
<p>Username: {{ user.username|upper }}</p>
<p>Number of posts: {{ posts|length }}</p>
<p>Summary: {{ post.content|truncatechars:50 }}</p>

upper → converts username to uppercase

length → counts number of posts

truncatechars → limits content to 50 characters

✅ Summary

Filters = modify the output of a variable

Syntax = {{ variable|filter_name[:argument] }}

Can chain multiple filters together

Default filter
include

Template {% include %} Tag


The {% include %} tag in Django templates allows the content of one template file
to be embedded (included) inside another template. This is especially useful for
reusing repeated elements like headers, footers, or menus across multiple pages.
● Basic usage:
● text

{% include "navbar.html" %}

● You can also pass variables:
● text

{% include "navbar.html" with user="Alex" %}



● To restrict the context to only the given variables:
● text

{% include "navbar.html" with user="Alex" only %}


This helps keep templates DRY (Don't Repeat Yourself), makes code cleaner, and
centralizes reusable UI components.
navbar.html
text

<nav>
Hello, {{ username }}!
</nav>

main.html
text

<!DOCTYPE html>
<html>
<body>
<!-- Include the navbar and pass 'username' variable -->
{% include "navbar.html" with username="Alex" %}

<h1>Welcome to the site</h1>


</body>
</html>

No, in Django templates you can load more than just static files or modules. The {%
load %} tag is used to import template tag libraries, which can include:
● Built-in Django template tag libraries like static, i18n, and humanize.
● Custom template tag libraries that you create inside your Django apps (inside
a templatetags package).
● Third-party template tag libraries provided by packages you install (like
django-simple-tags).

These libraries provide extra template tags and filters that you can use inside your
templates to add functionality, such as formatting data, custom logic, or rendering
dynamic content.

Examples beyond static files


● {% load static %} lets you use {% static %} for static files.
● {% load humanize %} lets you use filters like naturaltime to format dates.
● {% load your_custom_tags %} lets you use your own tags and filters that
you define in Python.
● {% load some_third_party_tags %} lets you use tags from libraries like
django-simple-tags.

Summary
● {% load %} is for loading template tag/filter libraries, not just static files.
● You must explicitly load any non-built-in template tags/filters you want to use.
● This system keeps templates clean and secure by controlling what features
are available per template.
Let me know if you want to see how to create and load custom tags or use popular
built-in libraries!The term "include" means to contain something as part of a whole.
In Django, "include" is mainly used in two ways: the {% include %} template tag,
which inserts the contents of one template inside another, and the include()
function in URL configuration to include URL patterns from other apps. In templates,
you can pass variables to the included template by using {% include
"template.html" with var=value %} syntax, allowing dynamic content reuse. The
{% load %} tag in Django templates loads template tag libraries (built-in, custom, or
third-party) to make their tags and filters available in the current template. It is not
limited to just static files or modules but includes any template tag library you want
to use. The {% block %} and {% endblock %} tags define sections of a template
that child templates can override; they must be used correctly with matching names
(or just {% endblock %}) to avoid syntax errors.

Template fragment caching in Django allows you to cache specific parts or


"fragments" of a template rather than the entire page. This is useful when certain
parts of a page take significant time or resources to render but other parts change
frequently and should not be cached.

How {% cache %} works


You add the {% load cache %} tag at the top of your template to enable cache
functionality.

You wrap the part of the template you want to cache with {% cache timeout
fragment_name %} ... {% endcache %}, where:

timeout is how long (in seconds) the content should be cached.

fragment_name is a unique identifier for this cache fragment.

Example:

text
{% load cache %}
{% cache 600 sidebar %}
<!-- Code for sidebar that takes long to render -->
{% endcache %}
The first time the template renders, Django processes the sidebar code normally and
stores the rendered HTML in the cache.

For the next 600 seconds (cache timeout), Django serves the cached HTML for the
sidebar without processing the original code again, improving performance.

After the timeout expires, the sidebar is rendered freshly and cached again.

Why use fragment caching?


It speeds up page rendering by avoiding repeated expensive template rendering for
certain sections.

Allows fine control by caching only parts that are costly and leaving the rest
dynamic.

Especially useful for expensive components like related posts, navigation menus, or
complex data lists.

Effective Template Fragment Caching in Django: Techniques and Use Cases | by


Ewho Ruth | Towards Dev

A Django model is a Python class that represents a single table in a database,


defining the structure of the data along with its fields and behaviors. Each attribute
of the model corresponds to a database field, and Django automatically creates an
API to interact with the database using these models, simplifying the process of
creating, reading, updating, and deleting database records. Models are usually
defined in the models.py file of a Django app and serve as the central source of
information about your data, allowing seamless database operations without writing
complex SQL queries.

Key aspects of Django models:


Each model maps to a database table.

Model attributes correspond to table columns.

Django adds an automatic primary key field if none is specified.

Models enable the use of Django's Object-Relational Mapper (ORM) to interact with
the database in Python code.

Models can include metadata and methods that define additional behaviors related
to the data.

Example:

python
from django.db import models

class Person(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
This example will create a database table with columns for first_name and
last_name, plus an automatically generated primary key id column.

In summary, Django models are Python classes that define how data is stored and
managed in the database, providing a clean and efficient way to work with databases
in Django applications.

What Are Django Models?


A Django model is a Python class that inherits from django.db.models.Model and
represents a single database table. Each attribute of the model represents a
database field, and Django automatically generates a database-access API for you

CharField - for small text like maxlength is 255


TextField - for big text
BigAutofield
Foreign Key – - on_delete = models.cascade
ImageField (upload_to=’path’) install pillow

when we use image we need to add settings

MEDIA_ROOT = BASE_DIR / ‘uploades’


MEDIA_URL = ‘/media’

also in urls

+ static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)

image adding
In Django, signals are a way for different parts of your application to communicate
with each other automatically — without writing extra code everywhere.

👉 Simple Definition:

A signal allows one piece of code (a “sender”) to send out a message


when something happens, and another piece of code (a “receiver”) can
automatically react to that message.

🧠 Real-world example:

Think of it like a doorbell system:

● When someone presses the doorbell (event happens),

● The bell rings inside the house (reaction happens).

You don’t need to check the door constantly — the signal system does it for you.

🧾 In Django:

Signals are usually used to run some code automatically when certain actions
happen, such as:

● When a user is created ✅

● When a model is saved ✅

● When a model is deleted ✅

Django gives us some built-in signals, like:

● post_save → after a model is saved

● pre_save → before a model is saved

● post_delete → after a model is deleted

● pre_delete → before a model is deleted

🧪 Example:
Let’s say you have a model:

# models.py
from django.db import models

class Student(models.Model):
name = models.CharField(max_length=100)
email = models.EmailField()

Now suppose you want to automatically print a message whenever a new student is
added.
Instead of modifying your views, you can use a signal:

# signals.py
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import Student

@receiver(post_save, sender=Student)
def student_created(sender, instance, created, **kwargs):
if created:
print(f"🎉 New student created: {instance.name}")

Then in your apps.py or __init__.py:

# apps.py or __init__.py of your app


def ready(self):
import myapp.signals

✅ Now, whenever you run:

Student.objects.create(name="Adith",
email="[email protected]")

You’ll see:

🎉 New student created: Adith

— automatically 🔥
⚡ Why signals are useful:

● You can separate logic cleanly (no need to put everything in views).

● Helps keep your code organized and reusable.

● Useful for tasks like:

○ Sending a welcome email after user signup 📧

○ Automatically creating a profile after a user is created 👤

○ Logging activities or updates 📜

⚠️When to use signals (and when not to):

● ✅ Use when something must always happen after an event (like creating
related data).

● ❌ Don’t overuse signals for everything — they can make your code
harder to debug if abused.

📝 Summary:

● Signals = automatic notifications inside Django.

● They connect a sender (event) with a receiver (function).

● Useful for doing tasks automatically when something happens.


CharField(max_le For small text name =
ngth=…) data (e.g., models.CharField(max_length=10
names, titles) 0)

TextField() For long text bio = models.TextField()


data (e.g.,
descriptions,
content)

IntegerField() For whole age = models.IntegerField()


numbers

FloatField() For decimal price = models.FloatField()


numbers

BooleanField() For True/False is_active =


values models.BooleanField(default=Tr
ue)

EmailField() Validates email = models.EmailField()


email format

DateField() / For storing created_at =


DateTimeField() dates and models.DateTimeField(auto_now_
times add=True)

ForeignKey() Creates department =


relationship to models.ForeignKey(Department,
another model on_delete=models.CASCADE)
(Many-to-One)

ImageField() / For uploading photo =


FileField() images or files models.ImageField(upload_to='p
hotos/')

🪝 3. Field Options (Attributes)


Option Description

max_length Required for CharField — sets max character length.

default Sets a default value.

null=True Allows storing NULL in the database.

blank=True Allows leaving the field empty in forms.

unique=True Ensures no duplicate values.

auto_now_add=True Automatically sets the date/time when the object is


created.

auto_now=True Updates the date/time every time the object is saved.

on_delete=models. Deletes related objects if the parent is deleted (used with


CASCADE ForeignKey).

Yes ✅ — In Django, SQLite is the default database when you create a new project.

That means — even if you don’t configure anything, Django will automatically create
and use a SQLite database file called db.sqlite3 in your project folder.

1. Why Django uses SQLite by default


● ✅ No setup required (it works out of the box)

● 🪶 Lightweight and file-based (no separate server needed)

● 🧪 Great for small projects, testing, or learning Django

● 🚀 Very fast for simple read/write operations

Django shell

The Django shell is an interactive Python shell environment that is specially set up to
work within a Django project, providing direct access to Django’s models, database,
and project settings for development, debugging, and experimentation.

How Django Shell Works


The Django shell can be started with the command:

text
python manage.py shell
When launched, it preloads your Django environment, so you can immediately
interact with models and the database using Django's ORM. This makes it easy to
perform quick database queries, create, read, update, and delete records, and test
Python logic in the context of your project.

Key Features
Directly manipulate Django models and query the database.

Debug code and test snippets interactively with full access to Django settings.

Supports enhanced shells like IPython and bpython for a richer interactive
experience.

Useful for running scripts, exploring the API, or experimenting with project modules,
migrations, and features.
Django Shell

obj = Customers(name='adith',age=20)
>>> obj
<Customers: adith 20>
>>> obj.save()

in this method we want also do obj.save()

another method is obj = Customers.objects.create(name=’adith’,age=20);


🧾 Example of your model (probably)
class Booking(models.Model):
product_name = models.CharField(max_length=100)
customer = models.ManyToManyField(Customer)

❌ Wrong way:
obj2 = Booking.objects.create(product_name="Chair", customer=obj1) #
❌ Not allowed

✅ Correct way:

You need to first create the Booking object without the M2M field, then use .set()
or .add().

# Create the booking first


obj2 = Booking.objects.create(product_name="Chair")

# Now set or add the customer


obj2.customer.add(obj1) # If obj1 is a single customer instance

# OR if you have multiple customers


# obj2.customer.set([obj1, obj2, ...])

📝 .add() is used to add one or more related objects.


.set() is used to set the entire list of related objects at once.

🔸 Extra Tip:

If customer should only point to one customer per booking, then it should be a
ForeignKey, not ManyToManyField.

customer = models.ForeignKey(Customer, on_delete=models.CASCADE)

Then you can do:

obj2 = Booking.objects.create(product_name="Chair", customer=obj1)

✅ Summary:
ManyToManyField → create first, then .add() or .set().

ForeignKey → assign directly in create().

What Happens When Using create() with Existing Records


Great question! You've identified an important distinction in Django ORM behavior.
When you use Model.objects.create() on a record that already exists in the database,
Django will raise an IntegrityError because create() always attempts an INSERT
operation.

The Key Difference in Detail


save() Method Behavior
Smart Operation: Checks if the object has a primary key value

If no primary key: Performs INSERT (creates new record)

If primary key exists: Performs UPDATE (modifies existing record)

No Error: Handles both new and existing objects gracefully

create() Method Behavior


Always INSERT: Attempts to create a new record regardless of existing data

Primary Key Conflict: Raises IntegrityError if a record with the same primary key
already exists

No Update Capability: Cannot modify existing records

Retrieving All Objects


To get all records from a model:
python

>>> all_objects = MyModel.objects.all()


>>> print(all_objects)

This returns a QuerySet containing all objects in the table.


Filtering Objects
The filter() method returns objects matching specific criteria:

python
>>> filtered_objects = MyModel.objects.filter(field_name='value')
>>> incomplete_tasks = Task.objects.filter(completed=False)

Getting a Single Object


The get() method retrieves exactly one object that matches the criteria:
python

>>> specific_object = MyModel.objects.get(id=1)


>>> user = User.objects.get(email='[email protected]')

Important: get() raises a DoesNotExist exception if no object is found, and


MultipleObjectsReturned if multiple objects match the criteria.
First and Last Objects:

python
>>> first_obj = MyModel.objects.first()
>>> last_obj = MyModel.objects.last()
These methods return None if no objects exist, avoiding exceptions.

Counting Objects:

python
>>> count = MyModel.objects.count()
>>> filtered_count = MyModel.objects.filter(status='active').count()
Checking Existence:

python
>>> exists = MyModel.objects.filter(name='test').exists()
The exists() method returns True if any objects match the criteria, False otherwise.

Practical Django Shell Session Example


Here's a complete example session working with a hypothetical Book model:

python
>>> from books.models import Book
>>>
>>> # Create a new book
>>> book1 = Book(title='Django for Beginners', author='William Vincent')
>>> book1.save()
>>>
>>> # Create another book using create()
>>> book2 = Book.objects.create(title='Two Scoops of Django', author='Daniel Roy
Greenfeld')
>>>
>>> # Retrieve all books
>>> all_books = Book.objects.all()
>>> print(all_books)
>>>
>>> # Filter books by author
>>> vincent_books = Book.objects.filter(author='William Vincent')
>>>
>>> # Get a specific book
>>> specific_book = Book.objects.get(title='Django for Beginners')
>>>
>>> # Check if books exist
>>> has_books = Book.objects.exists()
>>>
>>> # Count total books
>>> total_books = Book.objects.count()
Important QuerySet Characteristics
Django QuerySets are lazy, meaning they don't hit the database until you actually
need the data. This allows for efficient query optimization and chaining of operations
without unnecessary database calls.

QuerySets can be chained together for complex filtering:

python
>>> recent_active_users =
User.objects.filter(is_active=True).filter(date_joined__gte=some_

>>> file = Customers.objects.filter(age__lt = 20)


>>> print(file)
<QuerySet []>
>>> file = Customers.objects.filter(age__lt = 30)
>>> file
<QuerySet [<Customers: parthiv 28>, <Customers: adith 20>]>
>>> file = Customers.objects.filter(age__lt = 30)
>>> file
<QuerySet [<Customers: parthiv 28>, <Customers: adith 20>]>
>>> file = Customers.objects.get(id=1)
>>> file
<Customers: parthiv 28>

>> from books.models import Book


>>>
>>> # Create a new book
>>> book1 = Book(title='Django for Beginners', author='William Vincent')
>>> book1.save()
>>>
>>> # Create another book using create()
>>> book2 = Book.objects.create(title='Two Scoops of Django', author='Daniel Roy
Greenfeld')
>>>
>>> # Retrieve all books
>>> all_books = Book.objects.all()
>>> print(all_books)
>>>
>>> # Filter books by author
>>> vincent_books = Book.objects.filter(author='William Vincent')
>>>
>>> # Get a specific book
>>> specific_book = Book.objects.get(title='Django for Beginners')
>>>
>>> # Check if books exist
>>> has_books = Book.objects.exists()
>>>
>>> # Count total books

from django.db import models

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

class Meta:
ordering = ['name'] # Default order when querying authors
verbose_name = 'Writer' # Singular name in admin
verbose_name_plural = 'Writers' # Plural name in admin

def __str__(self):
return self.name
Common uses of Meta:
OptionWhat it does
ordering Default order of query results, e.g., ordering = ['name']
verbose_name Singular human-readable name for the model in admin
verbose_name_plural Plural name for admin
db_table Set a custom database table name instead of default
appname_modelname
unique_together Ensure combination of fields is unique
permissions Add custom permissions for this model
indexes Add database indexes for better query performance

Example with multiple Meta options:


python
Copy code
class Book(models.Model):
title = models.CharField(max_length=200)
author = models.ForeignKey(Author, on_delete=models.CASCADE)

class Meta:
ordering = ['title']
verbose_name = 'Book'
verbose_name_plural = 'Books'
unique_together = ('title', 'author') # No duplicate books for the same author

def __str__(self):
return self.title
✅ So, Meta is basically a place to configure how Django treats the model—
ordering, naming, uniqueness, etc.—without adding database fields.

Django Forms, Sessions & Custom


Authentication
Django forms, sessions, and custom authentication are fundamental building blocks
for creating interactive web applications. This comprehensive guide will take you
from beginner to advanced concepts, covering everything you need to implement
user input handling, session management, and authentication systems from scratch.
Creating and Handling User Input

Understanding Forms in Django


Django provides two main approaches to creating forms: manual creation using
forms.Form and automatic generation from models using ModelForm. Forms are
Python classes that represent HTML forms and handle validation, rendering, and
data processing.

Creating forms manually with forms.Form

from django import forms


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

VPSVPS for web devs

Apr 23, 2025

Andzelika D. & Ariffud M.

7min Read

How to use Django forms:


Creating, rendering and
handling forms
Summarize with:

ChatGPT

Claude.ai

Google AI

Grok

Perplexity

Share:

Django’s forms handling system uses Python classes to represent


forms as objects. These forms can be rendered in templates,
validated, and processed using just a few lines of code.
In this article, you’ll learn how to create forms, handle form
submissions, and use Django formsets.

○ Creating forms in Django


○ Creating forms manually with forms.Form
○ Generating forms from models using ModelForm
○ Rendering forms in Django templates
○ Simple rendering with helper functions
○ Custom rendering with HTML
○ Handling form submissions in Django views
○ Validating and processing forms
○ Customizing form error display
○ Displaying form errors in templates
○ Using the default error messages
○ Customizing error messages
○ Using Django formsets
○ Creating a formset
○ Using model formsets
○ Django forms FAQ
○ What are Django forms?
○ How do I create a form in Django?
○ How can I validate form data in Django?

Creating forms in Django


You can create forms in Django either manually with the Form
class or automatically generated from models using ModelForm.
To create a form in Django, define a form class in your forms.py
file. This class specifies the form fields and validation rules to
effectively process user input.

Creating forms manually with

forms.Form

Here’s an example of creating a simple contact form manually:


# forms.py

from django import forms

class ContactForm(forms.Form):

name = forms.CharField(max_length=100, label='Your Name')

email = forms.EmailField(label='Your Email')

message = forms.CharField(widget=forms.Textarea, label='Your


Message')

This form includes three fields: name, email, and message. Each
field is defined using Django’s form field classes:

● CharField for short text inputs like the name.


● EmailField for email validation.
● CharField with a Textarea widget for longer text inputs, such
as messages.

Generating forms from models using

ModelForm

In many cases, forms are tied to models. Django simplifies this by


letting you create forms directly from models using ModelForm.
This saves time by automatically generating form fields based on
the model’s fields.

● Creating a ModelForm form:

If you have a Post model in your models.py file:


# models.py

from django.db import models

class Post(models.Model):

title = models.CharField(max_length=200)

content = models.TextField()

created_at = models.DateTimeField(auto_now_add=True)

You can create a form for this model as follows:


# forms.py
from django import forms

from .models import Post

class PostForm(forms.ModelForm):

class Meta:

model = Post

fields = ['title', 'content']

● Using the ModelForm form in a view:

Next, use the form in your Django view like this:


# views.py

from django.shortcuts import render

from .forms import PostForm

def create_post(request):

if request.method == 'POST':

form = PostForm(request.POST)

if form.is_valid():

form.save() # Saves the form data to the database

return redirect('post_list') # Redirect to a list of


posts
else:

form = PostForm()

return render(request, 'create_post.html', {'form': form})

With ModelForm, Django automatically generates form fields


based on the model’s fields and handles saving the form to the
database with minimal boilerplate code.
VPSVPS for web devs

Apr 23, 2025

Andzelika D. & Ariffud M.

7min Read

How to use Django forms:


Creating, rendering and
handling forms
Summarize with:

ChatGPT

Claude.ai
Google AI

Grok

Perplexity

Share:

Django’s forms handling system uses Python classes to


represent forms as objects. These forms can be rendered in
templates, validated, and processed using just a few lines of
code.
In this article, you’ll learn how to create forms, handle form
submissions, and use Django formsets.

○ Creating forms in Django


○ Creating forms manually with forms.Form
○ Generating forms from models using ModelForm
○ Rendering forms in Django templates
○ Simple rendering with helper functions
○ Custom rendering with HTML
○ Handling form submissions in Django views
○ Validating and processing forms
○ Customizing form error display
○ Displaying form errors in templates
○ Using the default error messages
○ Customizing error messages
○ Using Django formsets
○ Creating a formset
○ Using model formsets
○ Django forms FAQ
○ What are Django forms?
○ How do I create a form in Django?
○ How can I validate form data in Django?

Creating forms in Django

You can create forms in Django either manually with the Form
class or automatically generated from models using
ModelForm.
To create a form in Django, define a form class in your
forms.py file. This class specifies the form fields and validation
rules to effectively process user input.

Creating forms manually with

forms.Form

Here’s an example of creating a simple contact form manually:


# forms.py

from django import forms

class ContactForm(forms.Form):

name = forms.CharField(max_length=100, label='Your Name')

email = forms.EmailField(label='Your Email')

message = forms.CharField(widget=forms.Textarea, label='Your


Message')

This form includes three fields: name, email, and message.


Each field is defined using Django’s form field classes:

● CharField for short text inputs like the name.


● EmailField for email validation.
● CharField with a Textarea widget for longer text inputs,
such as messages.
Generating forms from models using

ModelForm

In many cases, forms are tied to models. Django simplifies this


by letting you create forms directly from models using
ModelForm. This saves time by automatically generating form
fields based on the model’s fields.

● Creating a ModelForm form:

If you have a Post model in your models.py file:


# models.py

from django.db import models

class Post(models.Model):

title = models.CharField(max_length=200)

content = models.TextField()

created_at = models.DateTimeField(auto_now_add=True)

You can create a form for this model as follows:


# forms.py

from django import forms

from .models import Post


class PostForm(forms.ModelForm):

class Meta:

model = Post

fields = ['title', 'content']

● Using the ModelForm form in a view:

Next, use the form in your Django view like this:


# views.py

from django.shortcuts import render

from .forms import PostForm

def create_post(request):

if request.method == 'POST':

form = PostForm(request.POST)

if form.is_valid():

form.save() # Saves the form data to the database

return redirect('post_list') # Redirect to a list of


posts

else:

form = PostForm()

return render(request, 'create_post.html', {'form': form})


With ModelForm, Django automatically generates form fields
based on the model’s fields and handles saving the form to the
database with minimal boilerplate code.

Rendering forms in Django

templates

To display a form on a webpage, you need to render it in a


template. Django provides two approaches: using built-in
rendering helpers or rendering the form manually with HTML.

Simple rendering with helper functions

Django’s built-in helper functions make it easy to customize


how forms are displayed in templates. There are three methods
to render a form with different structures:

● form.as_p – wraps each form field in a <p> tag, ideal for


quick and clean styling.
● form.as_table – displays form fields in an HTML table,
useful for structured layouts.
● form.as_ul – wraps each field in <li> tags for list-style
formatting.

Here’s an example of using form.as_table:


<form method="post">

{% csrf_token %}

{{ form.as_table }}

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

</form>

● {% csrf_token %} – adds a CSRF token to protect against


cross-site request forgery attacks. This is required for
forms that use POST submission.

🧾 1. Using request.POST.get() (Recommended)

gender = request.POST.get('gender')
✅ Advantages:

Doesn’t raise an error if the key doesn’t exist (returns None


instead).

Safer than request.POST['gender'].

👉 You can also set a default value:

gender = request.POST.get('gender', 'not specified')

🧍 2. Using request.GET.get() for GET requests

If the data is sent using the GET method (like in a URL or query
string):
gender = request.GET.get('gender')

🧠 3. Accessing all POST data

data = request.POST

print(data) # shows all POST data

print(data.get('gender')) # get specific field

You can also convert it to a dictionary:

data_dict = request.POST.dict()

📬 4. Using request.data (Django REST Framework only)


If you’re working with Django REST framework:

gender = request.data.get('gender')

👉 Works for both POST and PUT requests (JSON or form data).

🧪 5. Using request.body (Raw data)

If you want the raw body of the request (for example, when
working with JSON):

import json

body = json.loads(request.body)

gender = body.get('gender')
✅ Best Practice:

Use request.POST.get('key') for form submissions.

Use request.data.get('key') if you’re building an API with DRF.

Use request.body + json.loads() if the data is sent as raw


JSON.

When you submit a form in Django using the classic POST method,
the browser makes a POST request to your backend. Django
processes that request, stores the data in the database, and then
typically renders a response.

The problem arises if the user refreshes the page after the form
submission.
👉 Modern browsers are designed to replay the last request on
refresh. So when the user refreshes after a POST, the browser
resends the exact same request payload — meaning the form
submission is executed again.

As a result:

The backend receives the same POST data a second time.

Your create() or save() logic runs again.

Duplicate records get inserted into the database.

This can lead to data integrity issues, double orders, duplicate


sign-ups, or inconsistent states.

This is known as the “duplicate form submission problem” or


“POST-refresh problem” — and it's not a Django bug. It’s standard
browser behavior.
🧭 How we solve it in real-world production apps

The industry-standard solution is to implement the PRG pattern —

Post → Redirect → Get.

Post: User submits the form with a POST request.

Redirect: The server processes the data and issues a redirect


response (302).

Get: The browser follows the redirect and loads the final page
with a GET request.

Why this works:

After the redirect, the last request in the browser’s history is


a GET.

So when the user refreshes, it only refreshes the GET page — not
the POST.
Attribute Description

min_length Minimum length allowed

label Custom display label for the field

initial Default value when the form first loads

help_text Small text hint shown below the input

error_messa Custom error messages

ges

widget Controls the HTML element (e.g.,


TextInput, PasswordInput)

name = forms.CharField(

label="Full Name",

max_length=100,

required=True,

help_text="Enter your full name.",

widget=forms.TextInput(attrs={'class': 'form-control',
'placeholder': 'Your name'})
)

Example (hidden field):

user_id = forms.UUIDField(widget=forms.HiddenInput(),

initial=uuid.uuid4)

address = forms.CharField(

widget=forms.Textarea(attrs={'rows': 3, 'cols': 40,


'placeholder': 'Enter your address'})

Field HTML Type Purpose

CharField text input Short text

EmailField email input Validates email


format

IntegerField number Whole numbers


input

FloatField number Decimal numbers


input

BooleanField checkbox True/False


DateField date input Date selection

ChoiceField dropdown/ Predefined


select options

MultipleChoiceF multi- Multiple


select choices
ield

FileField file upload Files

ImageField file upload Images only

URLField text input Validates URL


format

SlugField text input Slug-safe


string

UUIDField text input UUID validation

widget=forms.TextInput(attrs={

"class": "my-css-class",

"placeholder": "Enter your name",

"id": "name_field",

"required": True,
# Any other HTML attributes you want to add

})

🧱 1. Meta Class in Models

The Meta class inside a Django model controls how Django


interacts with the database, admin, and query behavior.

🔹 Example

class Student(models.Model):

name = models.CharField(max_length=100)

roll_no = models.IntegerField()
class Meta:

db_table = "student_table"

ordering = ['name']

verbose_name = "Student"

verbose_name_plural = "Students"

🧩 Full List of Model Meta Options

Option Description Example

db_table Custom table name in the database db_table =


"my_students"

ordering Default ordering of query results ordering =


['name']

verbose_name Human-readable name for the model (singular)


verbose_name = "Student Record"

verbose_name_plural Plural name for admin/site display


verbose_name_plural = "Student Records"

unique_together Fields that must be unique together


unique_together = ('name', 'roll_no')

index_together Fields that should have combined DB indexes


index_together = [['name', 'roll_no']]
constraints Advanced DB constraints (check, unique, etc.)
constraints = [models.UniqueConstraint(fields=['roll_no'],
name='unique_roll')]

permissions Define custom permissions permissions =


[('can_view_all', 'Can view all students')]

default_permissions Default: ('add', 'change', 'delete', 'view')


— can be overridden default_permissions = ()

get_latest_by Defines which field is used by .latest()


get_latest_by = 'created_at'

managed If False, Django doesn’t create/delete this table


managed = False

abstract If True, model won’t create a table (used for


inheritance) abstract = True

app_label Use if model is outside an app folder app_label =


'school'

db_tablespace Name of the database tablespace to use


db_tablespace = 'my_space'

default_related_name Default name for reverse relationships


default_related_name = 'students'

select_on_save Forces SELECT after saving (default False)


select_on_save = True

required_db_features Limits model to specific DB features


required_db_features = ['supports_transactions']
required_db_vendor Restrict to specific database vendor
required_db_vendor = 'postgresql'

indexes Create database indexes indexes =


[models.Index(fields=['name'])]

base_manager_name Default manager for model base_manager_name


= 'objects'

default_manager_name Default manager name for related fields


default_manager_name = 'objects'

proxy If True, makes it a proxy model (no table created) proxy =


True

✅ Use Case Example — controlling database, admin name, ordering,


and constraints.

🧾 2. Meta Class in Forms (ModelForm)

Used to define which model and fields the form should


include/exclude.

🔹 Example

from django import forms

from .models import Student


class StudentForm(forms.ModelForm):

class Meta:

model = Student

fields = ['name', 'roll_no']

labels = {'name': 'Full Name'}

help_texts = {'roll_no': 'Enter your roll number'}

error_messages = {'name': {'required': 'Name is


required!'}}

widgets = {'name': forms.TextInput(attrs={'class': 'form-


control'})}

🧩 Full List of Form Meta Options

Option Description Example

model Connects the form to a model model = Student

fields Include only specific model fields fields = ['name',


'roll_no']

exclude Exclude certain fields exclude = ['roll_no']

labels Custom labels for fields labels = {'name': 'Full


Name'}
help_texts Help text under each fieldhelp_texts = {'name': 'Enter
your full name'}

widgets Custom form widgets (HTML input style) widgets =


{'name': forms.TextInput(attrs={'class': 'form-control'})}

error_messages Custom error messages error_messages =


{'name': {'required': 'This field is required'}}

field_classes Custom field class per field field_classes =


{'name': MyCustomField}

✅ Use Case Example:

When you build a form from a model and want full control over how
it appears and behaves.

3. Meta in Admin (indirect)

Technically, admin.ModelAdmin doesn’t use its own Meta inner


class, but it reads metadata from the model’s Meta class (like
verbose_name, ordering, etc.).

You can also define display rules directly in the admin class:

from django.contrib import admin


from .models import Student

@admin.register(Student)

class StudentAdmin(admin.ModelAdmin):

list_display = ['id', 'name', 'roll_no']

ordering = ['name']

search_fields = ['name']

✅ The admin interface automatically uses:

verbose_name / verbose_name_plural

ordering

db_table (for raw SQL, not usually shown)

So, while Meta isn’t defined inside ModelAdmin, it affects how


the admin panel shows the model.
✅ Quick Summary Table

Area Purpose Common Options

Model Meta Database + admin settings db_table, ordering,


verbose_name, constraints, unique_together, abstract, managed

Form Meta Form behavior + appearancemodel, fields, exclude,


labels, widgets, help_texts, error_messages

Admin Reads from Model Meta verbose_name, ordering, etc.

🧭 Full Validation Flow Covered

Layer Purpose

✅ Validators Simple checks like


min/max

🧠 clean_<field>() Field-specific logic

🔀 clean() Cross-field logic

🧱 Model.clean() Database-level
business rules

DB constraints Final safety


🌐 (Optional) If you expose API
Serializer

GET Requests
● Used for retrieving data
● Parameters appear in URL
● Data is visible in browser history
● Limited data size
● Idempotent (safe to repeat)

POST Requests
● Used for sending/modifying data
● Data sent in request body
● More secure for sensitive data
● Larger data capacity
● Requires CSRF protection
🍪 1. COOKIES – Stored on the Browser (Client)

A cookie is a small piece of data stored in the user’s browser.

It is sent along with every request to the server.

Cookies can store any type of data (like username, theme,


language, or session_id).

Cookies are not secure if they store sensitive information in


plain text.
You can control how long a cookie lives (expiry date).

Data is stored in the browser itself.

✅ Example:

When you visit a shopping website and select a dark theme, the
browser stores:

theme=dark

Next time you open the site, it reads the cookie and shows the
dark theme.

📌 Real world:

It’s like a small note you keep in your pocket.


When you enter a shop, you show that note. The shopkeeper knows
who you are or what you want.

🧰 2. SESSIONS – Stored on the Server (Backend)

A session is stored in the server-side storage (like database,


cache, or memory).

The browser only gets a session ID (usually through a cookie).

Actual data (like user info, cart items, login state) stays safe
on the server.

Sessions are more secure than cookies because sensitive data


isn’t stored in the browser.

Sessions usually expire after some time (or on logout).

✅ Example:

When you log in to your account, Django saves:


session_id: abc123

user: Adith

is_logged_in: True

And your browser only has:

sessionid=abc123

📌 Real world:

It’s like keeping your details in a locker at the shop.

The shopkeeper gives you a locker key (session ID). When you come
again, you just show the key, and they access your stored data.

🆚 3. Cookies vs Sessions — Comparison Table

Feature Cookies 🧁 Sessions

Where stored Browser (client side) Server (backend)


Security Less secure (can be seen in browser) More secure (data
stored on server)

Data stored Key-value pairs directly Only session ID in


browser; data in server

Capacity Limited (around 4 KB) Much larger (depends on


server)

Lifetime Set by expiry date Ends on logout or timeout

Common use Theme, language, preferences Authentication, login


info, cart, sessions

Speed Faster (no server lookup) Needs server lookup

⚠️ 4. Cookie + Session Work Together

Cookie stores: sessionid=abc123

Session in server stores:

"abc123": {"user": "Adith", "is_logged_in": True}

👉 When the browser sends the cookie, Django uses the session ID
to find the data from the server.
✅ In short:

Cookie: small data stored in browser (client).

Session: large/secure data stored in server (backend).

Session usually uses cookies to work.

● request.session['key'] = value → Save a value

● request.session.get('key', default) → Get a value

● del request.session['key'] → Delete a specific key

● request.session.clear() → Remove all session data

● request.session.flush() → Clear and create a new session

📝 Example:

def my_view(request):
request.session['username'] = 'adith'

print(request.session.get('username')) # 'adith'

🧼 3. Session Lifecycle

● Sessions are stored on the server, and only a sessionid


cookie is stored in the browser.

● The session data is automatically expired after a certain


time (default is 2 weeks).

You can control how long the session lasts using:

request.session.set_expiry(3600) # seconds (1 hour)

🧾 4. Session Settings in settings.py

Important configuration options:

● SESSION_ENGINE – controls where session data is stored (db,

cache, file, etc.)

● SESSION_COOKIE_AGE – how long the session lasts


● SESSION_EXPIRE_AT_BROWSER_CLOSE – expires when the browser
closes

● SESSION_COOKIE_NAME – the name of the session cookie

(default sessionid)

🔐 5. Session Use Cases

● Storing login information (user_id)

● Shopping cart data (in e-commerce sites)

● Storing temporary messages or progress

● Counting visits or actions (like your count example)

🧭 6. Advanced Topics

● Custom session backends (database, cache, file system,


signed cookies)

● Secure sessions (HTTPOnly, Secure cookies)

Clearing expired sessions using:

python manage.py clearsessions


Example: Simple Login Session

def login_view(request):

username = request.POST.get('username')

password = request.POST.get('password')

# example check

if username == 'adith' and password == '1234':

request.session['is_logged_in'] = True

request.session['username'] = username

return HttpResponse('Login successful')

return HttpResponse('Invalid credentials')

def dashboard_view(request):

if request.session.get('is_logged_in'):

return HttpResponse(f"Welcome

{request.session['username']}")

return HttpResponse('Please log in')


When you want to logout a user and clear the session in Django,
the most commonly used and recommended method is:

request.session.flush()

✅ Why flush() is best:

● It deletes all session data for that user.

● It creates a new empty session with a new session key (helps


prevent session fixation attacks).

● It’s clean and safe.

You might also like