Introduction
In this section, we will explore how to build web applications using the Django framework. Django is a high-level Python web framework that encourages rapid development and clean, pragmatic design. It is known for its "batteries-included" philosophy, which means it comes with many built-in features to handle common web development tasks.
Key Concepts
-
Django Project vs. Django App:
- Project: The entire web application, including settings and configurations.
- App: A web application that does something, e.g., a blog, a forum, or a poll.
-
MVC Pattern:
- Model: Manages the data and business logic.
- View: Manages the user interface and presentation.
- Controller: Manages the input and interaction.
-
URL Routing:
- Maps URLs to views.
-
Templates:
- HTML files mixed with Django Template Language (DTL).
-
Forms:
- Handle user input and validation.
Setting Up a Django Project
Step 1: Install Django
Step 2: Create a Django Project
Step 3: Create a Django App
Step 4: Configure the Project
Edit myproject/settings.py
to include your new app:
URL Routing
Step 1: Define URLs in the App
Create a file myapp/urls.py
:
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), ]
Step 2: Include App URLs in the Project
Edit myproject/urls.py
:
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('myapp/', include('myapp.urls')), ]
Views
Step 1: Create a View
Edit myapp/views.py
:
from django.http import HttpResponse def index(request): return HttpResponse("Hello, world. You're at the myapp index.")
Templates
Step 1: Create a Template Directory
Create a directory myapp/templates/myapp/
and add an index.html
file:
<!DOCTYPE html> <html> <head> <title>My App</title> </head> <body> <h1>Hello, world. You're at the myapp index.</h1> </body> </html>
Step 2: Update the View to Use the Template
Edit myapp/views.py
:
Models
Step 1: Define a Model
Edit myapp/models.py
:
from django.db import models class Item(models.Model): name = models.CharField(max_length=100) description = models.TextField() created_at = models.DateTimeField(auto_now_add=True)
Step 2: Create and Apply Migrations
Step 3: Register the Model in the Admin
Edit myapp/admin.py
:
Forms
Step 1: Create a Form
Edit myapp/forms.py
:
from django import forms from .models import Item class ItemForm(forms.ModelForm): class Meta: model = Item fields = ['name', 'description']
Step 2: Use the Form in a View
Edit myapp/views.py
:
from django.shortcuts import render, redirect from .forms import ItemForm def create_item(request): if request.method == 'POST': form = ItemForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = ItemForm() return render(request, 'myapp/create_item.html', {'form': form})
Step 3: Create a Template for the Form
Create myapp/templates/myapp/create_item.html
:
<!DOCTYPE html> <html> <head> <title>Create Item</title> </head> <body> <h1>Create Item</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> </body> </html>
Practical Exercise
Task
- Create a new Django project and app.
- Define a model for a simple blog post with fields for title, content, and publication date.
- Create views to list all blog posts and to create a new blog post.
- Use templates to render the views.
- Implement forms for creating new blog posts.
Solution
- Create Project and App:
- Define Model:
Edit blogapp/models.py
:
from django.db import models class BlogPost(models.Model): title = models.CharField(max_length=200) content = models.TextField() pub_date = models.DateTimeField('date published')
- Create and Apply Migrations:
- Register Model in Admin:
Edit blogapp/admin.py
:
- Define URLs:
Edit blogapp/urls.py
:
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('create/', views.create_post, name='create_post'), ]
Include app URLs in blogproject/urls.py
:
from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('blogapp/', include('blogapp.urls')), ]
- Create Views:
Edit blogapp/views.py
:
from django.shortcuts import render, redirect from .models import BlogPost from .forms import BlogPostForm def index(request): posts = BlogPost.objects.all() return render(request, 'blogapp/index.html', {'posts': posts}) def create_post(request): if request.method == 'POST': form = BlogPostForm(request.POST) if form.is_valid(): form.save() return redirect('index') else: form = BlogPostForm() return render(request, 'blogapp/create_post.html', {'form': form})
- Create Forms:
Edit blogapp/forms.py
:
from django import forms from .models import BlogPost class BlogPostForm(forms.ModelForm): class Meta: model = BlogPost fields = ['title', 'content', 'pub_date']
- Create Templates:
Create blogapp/templates/blogapp/index.html
:
<!DOCTYPE html> <html> <head> <title>Blog Posts</title> </head> <body> <h1>Blog Posts</h1> <ul> {% for post in posts %} <li>{{ post.title }} - {{ post.pub_date }}</li> {% endfor %} </ul> <a href="{% url 'create_post' %}">Create New Post</a> </body> </html>
Create blogapp/templates/blogapp/create_post.html
:
<!DOCTYPE html> <html> <head> <title>Create Blog Post</title> </head> <body> <h1>Create Blog Post</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> </body> </html>
Conclusion
In this section, we covered the basics of building web applications with Django. We learned how to set up a Django project and app, define models, create views, use templates, and handle forms. By completing the practical exercise, you should now have a good understanding of how to build a simple web application using Django. In the next module, we will delve into data science with Python, starting with an introduction to data science concepts and tools.
Python Programming Course
Module 1: Introduction to Python
- Introduction to Python
- Setting Up the Development Environment
- Python Syntax and Basic Data Types
- Variables and Constants
- Basic Input and Output
Module 2: Control Structures
Module 3: Functions and Modules
- Defining Functions
- Function Arguments
- Lambda Functions
- Modules and Packages
- Standard Library Overview
Module 4: Data Structures
Module 5: Object-Oriented Programming
Module 6: File Handling
Module 7: Error Handling and Exceptions
Module 8: Advanced Topics
- Decorators
- Generators
- Context Managers
- Concurrency: Threads and Processes
- Asyncio for Asynchronous Programming
Module 9: Testing and Debugging
- Introduction to Testing
- Unit Testing with unittest
- Test-Driven Development
- Debugging Techniques
- Using pdb for Debugging
Module 10: Web Development with Python
- Introduction to Web Development
- Flask Framework Basics
- Building REST APIs with Flask
- Introduction to Django
- Building Web Applications with Django
Module 11: Data Science with Python
- Introduction to Data Science
- NumPy for Numerical Computing
- Pandas for Data Manipulation
- Matplotlib for Data Visualization
- Introduction to Machine Learning with scikit-learn