When it comes to learning the Django framework, there can be a lot to focus on, which could be very frustrating, especially for newbies who are still new to the world of technology. In this blog, I will talk about the 12 key concepts that every developer should know and master to become proficient in Django. The knowledge of these concepts will ensure that tech starters are able to build most of the functionalities you see on websites today as well as improve your skills, making you a potential candidate for a job. It is important to note, though, that learning these concepts comes with constant practice, the zeal for learning and relentlessness.
APPS: At the heart of every Django website are apps. Apps are small pieces of our projects that make up an entire website and are found in the main Django project directory. They are typically created to represent different sections of our websites such as the authentication, transactions etc. Usually, they contain the templates, URLs, views, and models. For example, if Django was used to build a platform such as Instagram or Facebook, you can have different apps/sections such as the app which is responsible for the "users" and contains the friends and photos in it, another app which contains the "feed" such as likes and comments, the "group" app which contains different groups created by the user etc. Before using apps, they need to be registered in the application setting found in the main Django project. Here's an example:
# Example of registering apps in Django project settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'your_app_name', # Replace 'your_app_name' with the name of your Django app ]
VIEWS: Views are simply functions that are in charge of handling the user request when a certain URL is visited. They are responsible for handling the entire request made by the users. For example, when a user is prompted to log in to his account, the view architecture is implemented, and the user has to be authenticated to log in. It is responsible for the logic in the backend and responds with the associated template.
# Example of a function-based view in Django from django.http import HttpResponse def my_view(request): return HttpResponse("Hello, world!")
Besides function based views, you can also write class based views in Django. However, I would recommend using function-based views for beginners. Here's a code sample which illustrates class-based views.
# Example of a class-based view in Django from django.views import View from django.http import HttpResponse class MyView(View): def get(self, request): return HttpResponse("Hello, world!")
URLs: To handle URL routing in a Django application, we create a list named urlpatterns and simply attach paths to that list. This is how Django knows which view to go to when a user visits a web application. When a URL is visited, Django searches the urlpatterns for the right path after which it checks the views attached to it.
# URLs configuration from django.urls import path from . import views urlpatterns = [ path('myurl/', views.my_view, name='my-view'), ]
TEMPLATES: As many of you would have guessed already, the template is where the front-end of the application is written. In the template, you will need to create the HTML file which is necessary as the structure of your web application.
<!-- Example of templates --> <!DOCTYPE html> <html> <head> <title>My Website</title> </head> <body> <h1>Hello, World!</h1> </body> </html>
STATIC FILES: Static files are essentially important to every website as they add visual layers to any application. When dealing with static files, we talk about the CSS, JavaScript, and images. These three are always in a static file known as “static.” While linking your stylesheet in Django, you do this using href="{% static 'index.css' %}." An example is illustrated below:
# Serving static files # In settings.py STATIC_URL = '/static/' # In template {% load static %} <link rel="stylesheet" href="{% static 'css/styles.css' %}">
MODELS: Models are simply class-based representations of our database tables. With the aid of models, we simply create a class that represents a table and the attributes in this class represent each column inside that database table.
# Example of defining a Django model from django.db import models class MyModel(models.Model): name = models.CharField(max_length=100) age = models.IntegerField()
Django ORM: Along with knowing how to design your database, you also need to know how to work with this database. Simple database operations such as
get()
,all()
, andfilter()
are how we retrieve items from the database using Django built-in ORM. A simple code illustrating this is:# Example usage of Django ORM # Get all objects MyModel.objects.all() # Filter objects MyModel.objects.filter(name='John') # Create a new object MyModel.objects.create(name='Jane', age=25)
ADMIN PANEL: Django provides us with a quick start interface to work with our table. Django also gives us an admin panel to view, create and update any data in our database. The admin panel is a great tool to start with and is also highly customizable. The admin panel is where all models are registered. Without registering this model, the data would not be available in the database even after migration. To register, the following is implemented as thus
# Registering models in admin.py from django.contrib import admin from .models import MyModel admin.site.register(MyModel)
CRUD OPERATIONS: While building most applications, you probably will have to perform CRUD operations at some point. CRUD stands for create, read, update and delete. Though, the admin panel helps you do all of these, you should learn how to create all these functionalities on your own. You can do all these from scratch using methods like the save and delete methods or we can use model forms and class based views that handle these functionalities for us. With any chosen method, you should learn how to perform these operations as it helps you learn how to code more.
# models.py from django.db import models class Product(models.Model): name = models.CharField(max_length=100) description = models.TextField() price = models.DecimalField(max_digits=10, decimal_places=2) # views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Product from .forms import ProductForm def product_list(request): products = Product.objects.all() return render(request, 'product_list.html', {'products': products}) def product_detail(request, pk): product = get_object_or_404(Product, pk=pk) return render(request, 'product_detail.html', {'product': product}) def product_create(request): if request.method == 'POST': form = ProductForm(request.POST) if form.is_valid(): form.save() return redirect('product_list') else: form = ProductForm() return render(request, 'product_form.html', {'form': form}) def product_update(request, pk): product = get_object_or_404(Product, pk=pk) if request.method == 'POST': form = ProductForm(request.POST, instance=product) if form.is_valid(): form.save() return redirect('product_list') else: form = ProductForm(instance=product) return render(request, 'product_form.html', {'form': form}) def product_delete(request, pk): product = get_object_or_404(Product, pk=pk) if request.method == 'POST': product.delete() return redirect('product_list') return render(request, 'product_confirm_delete.html', {'product': product})
In this example:
Product
is a simple Django model representing a product with fields like name, description, and price.The views
product_list
,product_detail
,product_create
,product_update
, andproduct_delete
handle the CRUD operations.product_list
displays a list of all products.product_detail
displays details of a specific product.product_create
andproduct_update
allow adding new products and updating existing ones respectively.product_delete
allows deleting a product.
AUTHENTICATION: Lucky for us, Django makes authentication very simple with all of its built in methods and forms. With this every beginner should be capable of handling user registration, login, logout and password reset functionality. With password reset there is however an added layer because you will need to understand how to configure emails in order to send out an email when a user requests a new password. Here's a simple code displaying how authentication works
# Example of user registration view from django.contrib.auth.forms import UserCreationForm def register(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() return redirect('login') else: form = UserCreationForm() return render(request, 'registration/register.html', {'form': form})
DJANGO COMMANDS: Django has numerous built-in commands for us to use but the 5 most common commands should be understood by every developer are:
# Creating a new Django project django-admin startproject <project-name> # Creating a new app within a project python manage.py startapp <app-name> # Creating migrations for changes in models python manage.py makemigrations # Applying migrations to the database python manage.py migrate # Creating a superuser for admin access python manage.py createsuperuser
Besides the built-in commands stated, the most popular necessary for running any project however is:
python manage.py runserver
DATABASE HANDLING: While Django does provide us with a SQLite database to store our details within our project, most companies require you to have additional knowledge of other database like MySQL or PostgreSQL. You need to know how to make this connection inside your settings and how to know how the database works.
CONCLUSION
Mastering Django's key concepts is fundamental for beginners in building robust web applications efficiently. From app creation to database management, authentication, and Django commands, each aspect plays a crucial role. Though they may be difficult at first, continuous practice and exploration of advanced features are essential for staying competitive in web development and the job market. With dedication, developers can unlock Django's full potential and create impactful solutions. Remember, coding isn't easy, but stay strong and keep pushing forward.