Django Tutorial: Creating Django Project

beginner
7 min

Django Tutorial: Creating Django Project

Welcome to our Django tutorial! In this comprehensive guide, we'll walk you through creating a Django project step-by-step. Django is a powerful, open-source web framework that encourages rapid development and clean, pragmatic design. Let's dive in!

🎯 Understanding Django

Django is a high-level Python web framework that simplifies the creation of complex web applications. It emphasizes reusability and the DRY (Don't Repeat Yourself) principle.

πŸ“ Installation

Before we start, ensure you have Python and Pip installed on your system. To install Django, open your terminal and type:

bash
pip install django

πŸ’‘ Creating a New Django Project

Now that Django is installed, let's create a new project. Open your terminal and type:

bash
django-admin startproject my_django_project

Replace my_django_project with the name you'd like for your project. This command creates a new Django project with a manage.py file and a project directory that contains an app called my_django_project.

🎯 Project Structure

Let's explore the structure of our newly created Django project:

my_django_project/ β”œβ”€β”€ manage.py β”œβ”€β”€ my_django_project/ β”‚ β”œβ”€β”€ __init__.py β”‚ β”œβ”€β”€ settings.py β”‚ β”œβ”€β”€ urls.py β”‚ └── wsgi.py └── my_django_project/ β”œβ”€β”€ __init__.py β”œβ”€β”€ migrations/ β”œβ”€β”€ static/ β”œβ”€β”€ templates/ └── apps/ └── my_app/ β”œβ”€β”€ __init__.py β”œβ”€β”€ migrations/ β”œβ”€β”€ models.py β”œβ”€β”€ tests.py β”œβ”€β”€ views.py └── admin.py

πŸ’‘ Running the Server

Navigate to your project directory and start the server using:

bash
cd my_django_project python manage.py runserver

Now, open your browser and visit http://127.0.0.1:8000/. You should see the Django welcome page!

πŸ“ Creating a New App

Let's create a new app called my_app within our project:

bash
python manage.py startapp my_app

πŸ’‘ Updating Project URLs

In your my_django_project/urls.py file, add the following to include the new app:

python
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('my_app.urls')), ]

Now, create a urls.py file in my_app directory and add the following:

python
from django.urls import path from . import views urlpatterns = [ path('', views.home, name='home'), ]

πŸ’‘ Creating a View

In my_app/views.py, create a simple view for our app's homepage:

python
from django.http import HttpResponse def home(request): return HttpResponse("Welcome to my_app!")

Now, if you refresh your browser, you should see "Welcome to my_app!" on the homepage.

Quick Quiz
Question 1 of 1

What command is used to create a new Django project?

Quick Quiz
Question 1 of 1

What is the purpose of the `manage.py` file in a Django project?