DJANGO
Django is a high-level, open-source web framework written in Python
that promotes rapid development and clean, pragmatic design. It’s
designed to help developers get their projects off the ground quickly and
easily without having to worry about the low-level stuff like thread
management, database connections, and so on.
Key Features of Django
Here are some of the key features that make Django a powerful choice
for web development:
MTV Architecture: Django follows the Model-Template-View
(MTV) architecture, which is a variant of the MVC (Model-View-
Controller) pattern. This makes it easier to manage different
components of your application.
ORM (Object-Relational Mapping): Django provides a robust
ORM that allows you to interact with your database using Python
code instead of SQL. This can simplify database interactions and
improve productivity.
Built-in Admin Interface: One of Django’s standout features is its
built-in admin interface, which is automatically generated from your
models. This interface allows you to manage your application’s
data easily.
Scalability: Django is designed to handle high-traffic websites. It
includes several tools and features to help optimize performance,
including caching, database optimization, and more.
Security: Django comes with a number of built-in security features
to protect your web applications from common security threats
such as SQL injection, cross-site scripting, and clickjacking.
Versatile and Flexible: Django can be used to build all sorts of
web applications, from content management systems (CMS) to
social networks and e-commerce platforms.
Getting Started with Django
To get started with Django, you need to have Python installed on your
system. Here are the basic steps to set up a Django project:
1. Install Django: You can install Django using pip, Python’s
package installer:
sh
pip install django
2. Create a New Project: Use Django’s startproject command to
create a new project:
sh
django-admin startproject myproject
or
python -m django startproject set4_1
3. Run the Development Server: Navigate to your project directory
and run the development server:
sh
python manage.py runserver
You can now visit http://127.0.0.1:8000/ in your web browser to
see your new Django project in action.
Virtual Environment
Setting up a Django project within a virtual environment is a good
practice. It helps in managing dependencies and keeping your project
isolated from other projects. Here are the steps to install and set up
Django in a virtual environment:
Step-by-Step Guide
1. Install Python: Ensure you have Python installed on your system.
You can check your Python version by running:
sh
python --version
If you don't have Python installed, you can download it from the
official Python website.
2. Install Virtualenv: To create a virtual environment, you first need
to install virtualenv. You can install it using pip:
sh
pip install virtualenv
3. Create a Virtual Environment: Create a new virtual environment
by running:
sh
virtualenv myenv
Replace myenv with the name you want for your virtual
environment.
4. Activate the Virtual Environment: Activate your virtual
environment:
o On Windows:
sh
myenv\Scripts\activate
o On macOS and Linux:
sh
source myenv/bin/activate
Phases in Django Project Creation Create a Project
Creating a Django project involves several phases. Here’s an overview
of each phase:
1. Setting Up the Environment
Before you begin, ensure you have Python and virtualenv installed. Set
up a virtual environment to manage your project dependencies and keep
your project isolated.
2. Creating a Django Project
Use the following command to create a new Django project:
sh
django-admin startproject projectname
This command creates a new directory with the project’s structure.
3. Creating a Django App
In Django, a project can contain multiple apps. Use the following
command to create a new app within your project:
sh
python manage.py startapp appname
An app is a module that encapsulates related functionality.
4. Configuring the Project
Edit the settings.py file to configure your project’s settings, such as
database configuration, installed apps, middleware, and static files.
5.Defining Models
MVT(Model View Template)
Define your database models in the models.py file of your app. Models
represent the structure of your data and allow Django to generate SQL
queries automatically.
6. Creating and Applying Migrations
Once your models are defined, create and apply migrations to update
your database schema:
sh
python manage.py makemigrations
python manage.py migrate
7. Creating Views
Define your views in the views.py file of your app. Views handle user
requests and return responses, such as rendering templates or returning
JSON data.
8. Mapping URLs
Create URL patterns in the urls.py file of your app to map views to
specific URLs. Include your app’s URL patterns in the project’s main
urls.py file.
9. Creating Templates
Create HTML templates for your app in a templates directory. Use
Django’s templating language to dynamically generate content.
10. Running the Development Server
Run the development server to test your project:
sh
python manage.py runserver
Visit http://127.0.0.1:8000/ to see your project in action.
11. Adding Static Files
Add static files (e.g., CSS, JavaScript, images) to your project in a static
directory. Configure static file handling in your settings.py file.
12. Testing Your Project
Write tests for your app in the tests.py file. Use Django’s testing
framework to ensure your code works as expected:
sh
python manage.py test
13. Deploying Your Project
When your project is ready for production, deploy it to a web server.
Configure your settings for production, including setting DEBUG = False,
configuring your database, and setting up static file serving.
Creation of Apps and their Structure
1. myproject (Your Project Directory):
This directory is the container for your entire Django project. It holds the
settings, URL configurations, and other project-level components.
myproject/ (Inner Project Directory): This is where the core
project files reside. It's also named myproject (or whatever you
named your project), which can be a little confusing at first.
o __init__.py: An empty file that tells Python to treat this
directory as a Python package.
o asgi.py: Asynchronous Server Gateway Interface file. Used
for deploying with ASGI servers (like Daphne). Handles
asynchronous requests.
o settings.py: The most important file in your project. It
contains all the configuration settings for your Django project
(database settings, static files, installed apps, etc.).
o urls.py: URL configuration for the entire project. It defines
the URL patterns that map incoming requests to views
(functions that handle the requests).
o wsgi.py: Web Server Gateway Interface file. Used for
deploying with WSGI servers (like Gunicorn or uWSGI).
Handles synchronous requests.
manage.py: A command-line utility that's crucial for interacting
with your Django project. You'll use this for running the
development server, making migrations, creating superusers, and
many other tasks.
2. myapp (Your Application Directory):
An app is a modular component of your Django project. You can have
multiple apps within a single project, each responsible for a specific set
of functionalities.
myapp/:
o __init__.py: Makes this directory a Python package.
o admin.py: Used for registering your models with the Django
admin interface. This makes your models manageable
through the admin panel.
o apps.py: Contains configuration for your app.
o migrations/: This directory stores migration files. These files
are how Django tracks and applies changes to your
database schema (when you modify your models).
__init__.py: Empty, makes the migrations directory a
package.
o models.py: Defines the data models for your app. These
models represent the structure of the data you'll be storing in
your database.
o tests.py: Used for writing unit tests for your app.
o views.py: Contains the view functions (or classes) that
handle incoming web requests and return responses (usually
HTML, JSON, etc.). This is where the logic of your app
resides.
o urls.py (Optional, but Highly Recommended): You can
create a urls.py file inside your app to define URL patterns
specific to that app. This is good practice for organizing your
URLs. If you don't have this file, you'll define all your URL
patterns in the project-level urls.py.
Example Workflow:
1. Create Project: django-admin startproject myproject
2. Create App: python manage.py startapp myapp
3. Define Models: Edit myapp/models.py to define your database
models.
4. Make Migrations: python manage.py makemigrations (in the
project directory)
5. Apply Migrations: python manage.py migrate (in the project
directory)
6. Write Views: Edit myapp/views.py to create functions that handle
requests and render templates.
7. Configure URLs: Edit myproject/urls.py (and optionally create
myapp/urls.py) to map URLs to your views.
8. Create Templates: Create HTML templates in the templates
directory (usually within your app directory:
myapp/templates/myapp/).
9. Run Server: python manage.py runserver
Example:Hello world
Step 1: Set Up Your Environment
1. Install Python: Ensure Python is installed on your system. You
can check the Python version by running:
sh
python --version
If Python is not installed, download it from the official Python
website.
2. Install Virtualenv: Install virtualenv to create a virtual
environment:
sh
pip install virtualenv
3. Create and Activate a Virtual Environment: Create a virtual
environment and activate it:
sh
virtualenv myenv
o On Windows:
sh
myenv\Scripts\activate
o On macOS/Linux:
sh
source myenv/bin/activate
Step 2: Install Django
With the virtual environment activated, install Django:
sh
pip install django
Step 3: Create a Django Project
Create a new Django project called myproject:
sh
django-admin startproject myproject1
cd myproject
Step 4: Create a Django App
Create a new app within the project called myapp:
sh
python manage.py startapp myapp
Step 5: Configure the Project
1. Add myapp to the INSTALLED_APPS list in myproject/settings.py:
python
# myproject/settings.py
INSTALLED_APPS = [
...
'myapp',
]
Step 6: Create Necessary Files and Code
1. myapp/views.py:
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def home(request):
return HttpResponse("hello world")
2. myapp/urls.py:
python
from django.urls import path
from . import views
urlpatterns = [
path(' ', views.home, name='home'),
]
3. myproject/urls.py:
python
from django.contrib import admin
from django.urls import include, path
urlpatterns = [
path('admin/', admin.site.urls),
path(' ', include('myapp.urls')),
]
Step 7: Run the Development Server
Run the development server to see your app in action:
sh
python manage.py runserver
Visit http://127.0.0.1:8000