What is Django? Install, first project, venv, settings, manage.py, urls. Deep dive into Model-View-Template
Before diving into Django, let's ensure you have a solid foundation in Python. Django is built on Python, so understanding Python fundamentals is crucial.
# Variables and Data Types
name = "Django Developer"
age = 25
is_learning = True
skills = ["Python", "Django", "HTML", "CSS"]
# Functions
def greet(name):
return f"Hello, {name}! Welcome to Django!"
# Classes
class Developer:
def __init__(self, name, skills):
self.name = name
self.skills = skills
def add_skill(self, skill):
self.skills.append(skill)
return f"Added {skill} to skillset"Key Python concepts you should be familiar with: variables, data types, functions, classes, lists, dictionaries, and basic control structures.
Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It follows the Model-View-Template (MVT) architectural pattern.
Django was created by Adrian Holovaty and Simon Willison in 2003 and was released publicly in 2005. It's named after the jazz guitarist Django Reinhardt.
Setting up a proper development environment is crucial. We'll use virtual environments to isolate our Django projects.
# Create a new directory for your project
mkdir django-course
cd django-course
# Create a virtual environment
python -m venv venv
# Activate the virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Install Django
pip install django
# Verify installation
python -m django --versionVirtual environments are essential because they allow you to have different versions of Python packages for different projects without conflicts.
Let's create your first Django project and understand the basic structure.
# Create a new Django project
django-admin startproject myproject
cd myproject
# The project structure will be:
myproject/
├── manage.py
└── myproject/
├── __init__.py
├── settings.py
├── urls.py
├── asgi.py
└── wsgi.pyThe `django-admin startproject` command creates the basic structure for a Django project. Let's explore each file:
Understanding the difference between Django apps and projects is crucial for building well-organized applications.
Think of a project as a website, and apps as the different features or sections of that website. For example, a blog website might have apps for 'blog posts', 'comments', 'user authentication', etc.
Apps are the building blocks of Django applications. Let's learn how to create and configure them.
# Create a new app
python manage.py startapp blog
# The app structure will be:
blog/
├── __init__.py
├── admin.py
├── apps.py
├── models.py
├── tests.py
├── urls.py (you'll create this)
├── views.py
└── migrations/
└── __init__.pyAfter creating an app, you need to register it in your project's settings.py file:
# settings.py
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'blog', # Add your new app here
]Apps should be focused on a specific functionality. Common app names include 'blog', 'users', 'products', 'orders', etc.
Each Django app has a specific file structure. Understanding these files is essential for building Django applications.
# admin.py
from django.contrib import admin
from .models import Post, Comment
@admin.register(Post)
class PostAdmin(admin.ModelAdmin):
list_display = ['title', 'author', 'created_date']
list_filter = ['created_date', 'author']
search_fields = ['title', 'content']
@admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ['post', 'author', 'created_date']
list_filter = ['created_date', 'author']# apps.py
from django.apps import AppConfig
class BlogConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'blog'
verbose_name = 'Blog'# models.py
from django.db import models
from django.contrib.auth.models import User
class Post(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.ForeignKey(User, on_delete=models.CASCADE)
created_date = models.DateTimeField(auto_now_add=True)
updated_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
class Meta:
ordering = ['-created_date']# views.py
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Post
def post_list(request):
posts = Post.objects.all()
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
@login_required
def post_create(request):
# Logic for creating a new post
pass# urls.py (create this file in your app)
from django.urls import path
from . import views
app_name = 'blog'
urlpatterns = [
path('', views.post_list, name='post_list'),
path('<int:pk>/', views.post_detail, name='post_detail'),
path('create/', views.post_create, name='post_create'),
]You'll also need to create a templates directory in your app for HTML templates, and optionally a static directory for CSS, JavaScript, and images.
The `manage.py` file is Django's command-line utility for administrative tasks. It's your primary tool for interacting with your Django project.
# Run the development server
python manage.py runserver
# Create database tables
python manage.py migrate
# Create a new app
python manage.py startapp myapp
# Create a superuser
python manage.py createsuperuser
# Collect static files
python manage.py collectstatic
# Shell for interactive Python
python manage.py shellThese commands are essential for Django development. You'll use them frequently throughout your Django journey.
The `settings.py` file contains all the configuration for your Django project. Understanding these settings is crucial for proper project setup.
# settings.py
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'your-secret-key-here'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'myapp', # Your custom app
]
# Database configuration
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Static files (CSS, JavaScript, Images)
STATIC_URL = 'static/'
# Media files
MEDIA_URL = '/media/'
MEDIA_ROOT = BASE_DIR / 'media'These settings control everything from database configuration to static files handling. We'll explore more settings as we progress.
URLs in Django are the entry points to your application. They map web addresses to Python functions (views).
# myproject/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('myapp.urls')), # Include app URLs
]
# myapp/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name='home'),
path('about/', views.about, name='about'),
path('contact/', views.contact, name='contact'),
]URL patterns use regular expressions to match URLs and route them to the appropriate view functions.
Django follows the Model-View-Template (MVT) architectural pattern, which is a variation of the Model-View-Controller (MVC) pattern.
# models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=200)
content = models.TextField()
author = models.CharField(max_length=100)
published_date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
class Meta:
ordering = ['-published_date']# views.py
from django.shortcuts import render
from .models import Article
def home(request):
articles = Article.objects.all()
return render(request, 'home.html', {'articles': articles})
def article_detail(request, article_id):
article = Article.objects.get(id=article_id)
return render(request, 'article_detail.html', {'article': article})<!-- templates/home.html -->
<!DOCTYPE html>
<html>
<head>
<title>My Django Blog</title>
</head>
<body>
<h1>Welcome to My Blog</h1>
{% for article in articles %}
<article>
<h2>{{ article.title }}</h2>
<p>By {{ article.author }}</p>
<p>{{ article.content|truncatewords:50 }}</p>
<a href="{% url 'article_detail' article.id %}">Read more</a>
</article>
{% endfor %}
</body>
</html>The MVT pattern promotes separation of concerns, making your code more maintainable and testable. Models handle data, Views handle logic, and Templates handle presentation.