Basic Modules
Object-relational mapper
In Django, the Object-Relational Mapper (ORM) is a layer of abstraction that enables you to interact with databases using Python objects instead of SQL statements. The ORM maps Python classes to database tables, and instances of those classes to rows in the tables.
The Django ORM provides a simple and intuitive API for performing common database operations such as creating, updating, and querying records. You can use the ORM to define your database schema using Python classes, and then interact with the database using instances of those classes.
from django.db import models
class User(models.Model):
"""A model that can intract with User Table."""
email = models.EmailField(max_length=200)
password = models.CharField(max_length=128)
class Student(models.Model):
"""A model that can intract with Student Table."""
name = models.CharField("Student's name", max_length=200)
gender = models.CharField(choices=(
('f', "Female"),
('m', "Male"),
('o', "Others"),
),
max_length=1
)
user = models.ForeignKey(User, on_delete=models.CASCADE)
You can still write SQL if needed. I will explain it in later topics.
URLs and views
In Django, URLs and views are used to map incoming requests to the appropriate view function. The view function then generates a response that is returned to the client.
URLs in Django are defined in the urls.py files of your application or project. Each URL maps a URL pattern to a view function. URLs can include named parameters that are passed to the view function as arguments. For example:
from django.urls import path
from . import views
urlpatterns = [
path('users/', views.user_listing, name='user-list'),
path('users/<int:band_id>/', views.user_detail, name='user-detail'),
path('users/search/', views.user_search, name='user-search'),
]
from django.shortcuts import render
from bands.models import Band
def user_listing(request):
"""A view of all users."""
users = User.objects.all()
return render(request, 'users/user_listing.html', {'users': users})
Templates
Templates in Django are typically written in the Django Template Language (DTL), which is a syntax that allows you to embed dynamic content in your HTML pages. DTL includes a number of constructs, such as loops, conditionals, and filters, that make it easy to generate complex HTML pages.
Here's an example of a simple template that uses DTL to include dynamic content:
<html>
<head>
<title>User Listing</title>
</head>
<body>
<h1>All Users</h1>
<ul>
{% for user in users %}
<li>
<h2><a href="{{ user.get_absolute_url }}">{{ user.email }}</a></h2>
{% if user.email %}
<p>This user has email.</p>
{% endif %}
</li>
{% endfor %}
</ul>
</body>
</html>
Forms
Django Forms provide a simple way to handle HTML forms and its data in a reusable and standardized way. It allows developers to quickly and easily create forms, validate input data and handle errors.
Django Forms are defined as Python classes that inherit from django.forms.Form or django.forms.ModelForm and declare fields as class attributes. Each field maps to a form input element, and can have its own validation rules.
Here is an example of a simple Django form that accepts a email and a password:
from django import forms
class UserCreateForm(forms.Form):
email = forms.CharField(max_length=100)
password = forms.CharField(label="Password", max_length=30, widget=forms.PasswordInput)
Decorators
In Django, a decorator is a special type of function that is used to modify or extend the behavior of another function. Decorators can be used to add functionality to a view function, check if a user is authenticated, cache data, log data, and more.
Decorators are defined using the @ symbol followed by the decorator name, and are applied to the function or class that is being decorated. For example, the @login_required decorator is used to restrict access to views that require the user to be authenticated:
@login_required
def my_protected_view(request):
"""A view that can only be accessed by logged-in users"""
return render(request, 'protected.html', {'current_user': request.user})
Decorators can also be used to define custom behavior for views. For example, the following custom decorator logs the time taken to execute a view:
import time
def log_time(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__} took {end_time - start_time} seconds to execute")
return result
return wrapper
@log_time
def my_view(request):
# Log the time taken to execute this view
Admin
In Django, the admin site is a built-in feature that allows superusers to manage the application's data models and content easily. The admin site is dynamically generated based on the registered models and their fields, making it easy to view, create, update, and delete objects.
from django.contrib import admin
from bands.models import User, Student
class StudentAdmin(admin.ModelAdmin):
"""Customize the look of the auto-generated admin for the Student model"""
list_display = ('name', 'gender')
list_filter = ('gender',)
admin.site.register(User) # Use the default options
admin.site.register(Student, StudentAdmin) # Use the customized options
Internationalization
Internationalization (often abbreviated as "i18n") is the process of designing and implementing software applications that can be adapted to different languages and cultures. In Django, internationalization is built-in and makes it easy to translate the text and other content of your application into multiple languages.
path('/', views.homepage, name='home'),
from django.shortcuts import render
from django.utils.translation import gettext
def homepage(request):
"""
Shows the homepage with a message that can be translated in the
user's language.
"""
message = gettext('This documentation is writen by Abubakar Zorrain')
url= 'https://github.com/AbubakarZorrain'
return render(request, 'homepage.html', {'message': message, 'url': url})
{% load i18n %}
<html>
<head>
<title>{% trans 'Django-MercurySols' %}</title>
</head>
<body>
{# Translated in the view: #}
<p>
{% blocktrans %}<a href="{{url}}"> {{ message }} </a>{% endblocktrans %}
</p>
</body>
</html>