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

Django

Django is a high-level, open-source web framework written in Python that facilitates rapid development and clean design through features like MTV architecture, ORM, and a built-in admin interface. To start a Django project, one must install Python, set up a virtual environment, and follow a series of steps to create a project and app, define models, and configure views and URLs. The document also provides an example workflow for creating a simple 'Hello World' application and details on working with models, views, and the Django admin console.

Uploaded by

Akshat Joshi
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)
0 views

Django

Django is a high-level, open-source web framework written in Python that facilitates rapid development and clean design through features like MTV architecture, ORM, and a built-in admin interface. To start a Django project, one must install Python, set up a virtual environment, and follow a series of steps to create a project and app, define models, and configure views and URLs. The document also provides an example workflow for creating a simple 'Hello World' application and details on working with models, views, and the Django admin console.

Uploaded by

Akshat Joshi
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
You are on page 1/ 16

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:

myenv\Scripts\activate

o On macOS and Linux:

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:

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:

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:

python --version

If Python is not installed, download it from the official Python


website.

2. Install Virtualenv: Install virtualenv to create a virtual


environment:

pip install virtualenv

3. Create and Activate a Virtual Environment: Create a virtual


environment and activate it:

virtualenv myenv

o On Windows:

myenv\Scripts\activate

o On macOS/Linux:

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:

from django.urls import path


from . import views

urlpatterns = [
path(' ', views.home, name='home'),
]

3. myproject/urls.py:
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

python manage.py runserver


Visit http://127.0.0.1:8000
Working with ADMIN Console. Creating Views URL Mapping.
Template System Working with Models.
# myapp/models.py

from django.db import models

class Student(models.Model):
name = models.CharField(max_length=200)
age = models.IntegerField()
email = models.EmailField(blank=True,
null=True)
grade = models.CharField(max_length=50,
blank=True, null=True)

def __str__(self):
return self.name

# myapp/admin.py

from django.contrib import admin

# Register your models here.


from .models import Student

admin.site.register(Student)

# myapp/views.py

from django.shortcuts import render, redirect


from .models import Student
from .forms import StudentForm

def student_list(request):
students = Student.objects.all()
return render(request,
'myapp/student_list.html', {'students':
students})
def student_create(request):
if request.method == 'POST':
form = StudentForm(request.POST)
if form.is_valid():
form.save()
return redirect('student_list')
else:
form = StudentForm()
return render(request, 'student_form.html',
{'form': form})

# myapp/forms.py

from django import forms


from .models import Student

class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = '__all__'

# myapp/urls.py

from django.urls import path


from . import views

urlpatterns = [
path('', views.student_list,
name='student_list'),
path('create/', views.student_create,
name='student_create')
]

# myproject/urls.py

from django.contrib import admin


from django.urls import path, include

urlpatterns = [
path('admin/', admin.site.urls),
path('myapp/', include('myapp.urls')),
path('', include('myapp.urls')), # Add this
line to handle the root URL
]

# myapp/templates/myapp/student_list.html

<h1>Student List</h1>
<a href="{% url 'student_create' %}">Create
Student</a>

<table>
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Grade</th>
</tr>
</thead>
<tbody>
{% for student in students %}
<tr>
<td>{{ student.name }}</td>
<td>{{ student.age }}</td>
<td>{{ student.email }}</td>
<td>{{ student.grade }}</td>
</tr>
{% endfor %}
</tbody>
</table>

# myapp/templates/student_form.html (No changes)


<h1>Student Form</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Save</button>
</form>

<a href="{% url 'student_list' %}">Back to


List</a>

1.Create Environmental variable

python –m venv dj

dj\Scripts\activate

2. Run Migrations (To Create Database Tables):

 This command creates the database tables based on your


myapp/models.py file.

Bash

python manage.py makemigrations


python manage.py migrate

3. Run the Development Server:

 This starts the Django development server, allowing you


to view your app in your web browser.

Bash

python manage.py runserver

 Open your web browser and go to http://127.0.0.1:8000/ to


see your app.

4. Create a Superuser (For Admin Access):


 This creates an administrative user account that you can
use to log in to the Django admin panel.

Bash

python manage.py createsuperuser

 Follow the prompts to enter a username, email address


(optional), and password.

5. Access the Django Admin Console:

 After creating a superuser, open your web browser and go


to:
 http://127.0.0.1:8000/admin/
 Enter the username and password you created with
createsuperuser.

You might also like