Framework and Django
Notes from the summary of COMP3011 Lecture 1, 2, 3 and online resources.
What is a Framework?
A framework provides a reusable and standardized foundation for developing software. It includes pre-written libraries, APIs, and tools to streamline development. Frameworks emphasize efficiency, maintainability, and scalability.
In this unit, we’ll explore web development frameworks including Django, Bootstrap, Express, Node.js, and React.
Django Structure and Key Files
Project-Level Files
__init__.py: Marks a directory as a Python package.settings.py: Stores configurations like database, apps, middleware.urls.py: Maps URLs to view functions.wsgi.py: Entry point for WSGI-compatible servers.manage.py: CLI tool for managing the project.
App-Level Files
admin.py: Registers models to the admin interface.apps.py: App metadata and configuration.models.py: Defines database models.tests.py: Contains test cases.urls.py: App-specific routes.views.py: Contains request-handling logic.
Django Architecture: Model-View-Template (MVT)
Django follows the MVT pattern (a variant of MVC):
- Model: Manages data and defines the schema (
models.py). - View: Handles application logic and returns responses (
views.py). - Template: Controls presentation using Django’s templating language (
templates/).
Benefits of MVC/MVT
- Promotes code reusability and maintainability.
- Clean separation of concerns for data, logic, and presentation.
Models and Migrations
Models define database structure and relationships. Before writing a model, plan the fields (e.g., title, description, slug, tags). Use slugs for cleaner, SEO-friendly URLs.
After writing models:
python3 manage.py makemigrations
python3 manage.py migrate
Django Admin Interface
The admin panel is an internal tool for managing data. To enable it:
from django.contrib import admin
from .models import Post
admin.site.register(Post)
Run the server and access http://127.0.0.1:8000/admin/.
python3 manage.py createsuperuser
Templates and Dynamic Rendering
Django templates use control structures ({% ... %}) and variables ({{ ... }}).
Example view:
def index(request):
posts = Post.objects.all()
return render(request, 'index.html', {'posts': posts})
Example template:
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.description }}</p>
{% endfor %}
You can extend templates using base.html with {% extends “base.html” %}.
URLs and Routing
Django uses urls.py to route requests.
Project urls.py:
path('books/', include('books.urls'))
App urls.py:
path('', views.index),
path('<book_id>', views.detail, name='books_detail')
Error Handling
- 404: Page not found. Use
get_object_or_404()to handle missing resources. - 500: Server errors.
- 400/403: Bad request / Forbidden.
Custom error pages can be designed for production.
APIs in Django
APIs allow systems to exchange data. RESTful APIs use GET, POST, PUT, DELETE methods. Django supports API development with frameworks like Tastypie and Django REST Framework (DRF).
Tastypie simplifies exposing models as APIs and allows fine control over access.
CSRF Protection
Django protects against Cross-Site Request Forgery via {% csrf_token %} in forms.
The middleware checks for a per-request token and blocks mismatches.
Use CSRF tokens when modifying or accessing protected data.
Summary
- Django is a high-level Python web framework that follows the MVT pattern.
- It simplifies CRUD operations, template rendering, routing, and admin interfaces.
- Key tools include migrations, templating, and REST APIs.
- Django promotes clean architecture and is well-suited for scalable, secure web development.
Leave a comment