A Django app is a self-contained module in a Django web framework that encapsulates a specific functionality for a website. It consists of a collection of models, views, templates, and other components that are organized in a specific directory structure. The app can be reused in multiple projects and can be easily plugged into a Django project to add additional functionality. A Django project can consist of multiple apps, each of which contributes to the overall functionality of the website.
If you haven't install python and django you can start from here Installing python and django
For Quick Setup
Create a virtual environment
python -m venv env
Activate virtual environment
source env/bin/activate
Installing Django
pip install django
Creating your first Project
django-admin startproject projectname
Creating your first App
Change to project directory: "cd projectname"
django-admin startapp appname
you see app have its own file structure, hence it is independent of the project. To work with app we need to include it in project
projectname/projectname/settings.py
# Application definition
INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"whitenoise.runserver_nostatic",
"django.contrib.sitemaps",
"appname", # <-- add this
]
Inside appname directory create a directory with name "templates"
This directory contains your html files
Now, Create a html file "home.html" in templates
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
Create View
Create views in the views.py file of the app folder to handle HTTP requests
projectname/appname/views.py
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
Create Url
To access urls of app you need add app's urls in project's urls
projectname/projectname/urls.py
from django.contrib import admin
from django.urls import path
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('appname.urls')), # <-- add this
]
Now create a file inside appname directory with name "urls.py"
projectname/appname/urls.py
from django.urls import path
from appname import views
urlpatterns = [
path('', views.home, name='home'), # <-- add this
]
Start the development server
python manage.py runserver
Access the website at http://localhost:8000.