Introduction to Django
Django is a high-level Python web framework that allows developers to build robust and scalable web applications quickly. It follows the “batteries-included” philosophy, meaning it comes with a wide range of built-in features like user authentication, admin interface, and more.
Whether you’re a student, a developer transitioning to web development, or a complete beginner, this tutorial will walk you through creating your first Django project step-by-step.
What You’ll Learn
- How to install Django
- Create your first Django project and app
- Understand the MTV (Model-Template-View) architecture
- Build models and use the Django admin
- Create dynamic views and URLs
- Use templates to build HTML pages
- Run and test your Django web application
Prerequisites
- Basic knowledge of Python
- Python installed on your system (Python 3.10+ recommended)
- Code editor (VS Code recommended)
- Terminal/Command Prompt
Step 1: Install Django
pip install django
django-admin --version
Step 2: Create a Django Project
django-admin startproject myproject
cd myproject
python manage.py runserver
Visit http://127.0.0.1:8000/
to confirm your project is running.
Step 3: Create a Django App
python manage.py startapp myapp
Then, register your app in settings.py
:
INSTALLED_APPS = [
...
'myapp',
]
Step 4: Understand the MTV Architecture
- Model: Defines the data structure (database tables).
- Template: Controls how data is presented (HTML).
- View: Handles logic and connects model to template.
Step 5: Create Your First Model
Edit myapp/models.py
:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
def __str__(self):
return self.title
python manage.py makemigrations
python manage.py migrate
Step 6: Use Django Admin
python manage.py createsuperuser
Login at /admin/
and add your data via the admin dashboard.
Step 7: Create Views and URLs
Edit myapp/views.py
:
from django.http import HttpResponse
def home(request):
return HttpResponse("Welcome to Django!")
Create myapp/urls.py
:
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Include this in myproject/urls.py
:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')),
]
Step 8: Create Templates
Create a file at templates/myapp/home.html
:
<!DOCTYPE html>
<html>
<head><title>Django App</title></head>
<body>
<h1>Welcome to Django!</h1>
</body>
</html>
Modify the view:
from django.shortcuts import render
def home(request):
return render(request, 'myapp/home.html')
Conclusion
Congratulations! You’ve just created your first Django web app. From project setup to creating templates and views, you’ve covered the fundamentals. Next, explore Django forms, user authentication, REST APIs, and deployment options.
Stay tuned for more tutorials and subscribe to our blog for updates!