2. Create Backend

After the Main Setup we can configure our App:

Main Process

In the Django Project App:

  1. Models | We create a Database Model under models.py
  2. Serializer | We will create the serializer.py file to convert complex data in JSON or other formats.
  3. Views | We will create our View under views.py
  4. URL’s - Backend | We will put the trigger under urls.py outside the Project App in the main Folder!
  5. URL’s - App specific | Create URLs in the App and Register App Views and Routers
  6. Admin.py | Add to admin.py File, Register the App

Here’s a simplified workflow illustration for how Django processes the configuration and interacts with various components like models, serializers, views, URLs, and the admin panel:

workflow.png


Database Model

The example code looks like this:

from django.db import models

class Todo(models.Model):
    body = models.CharField(max_length=300)
    completed = models.BooleanField(default=False)
    updated = models.DateTimeField(auto_now=True)
    created = models.DateTimeField(auto_now_add=True)

Explanation:

This Python code defines a Django model named “Todo” that represents a simple representation of a to-do list. Let’s go through each line in detail:

  1. from django.db import models: This line imports the models class from the Django package django.db. Django uses Object-Relational Mapping (ORM) to facilitate database interactions. The models module contains classes that serve as models for database tables.

  2. class Todo(models.Model):: Here, a new class Todo is created, inheriting from the Django Model class. By inheriting from models.Model, this object becomes a Django model that is represented in the database as a table.

  3. body = models.CharField(max_length=300): This line defines a field body that contains the actual text of the task. It is defined as a string (CharField) with a maximum length of 300 characters.

  4. completed = models.BooleanField(default=False): This completed field is a boolean field indicating whether the task is completed or not. It has a default value of False, meaning that a task is considered incomplete by default.

  5. updated = models.DateTimeField(auto_now=True): The updated field is a DateTimeField that stores the timestamp of the last update of the task. The auto_now=True ensures that the field is automatically updated to the current time when the object is saved.

  6. created = models.DateTimeField(auto_now_add=True): The created field is also a DateTimeField that stores the timestamp of when the task was created. The auto_now_add=True ensures that the field is automatically set to the current time when the object is created and remains unchanged afterward.


Serializers

The example code looks like this:

from rest_framework import serializers
from . import models

class TodoSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Todo
        fields = "__all__"

Explanation:

  1. from rest_framework import serializers: This line imports the serializers class from the Django REST Framework. Serializers are used to convert complex data structures such as Django models into JSON or other data formats that can be easily transmitted over the internet.

  2. from . import models: Here, the local models module is imported. This indicates that there is a Django app model named Todo in the same directory (package) as this code.

  3. class TodoSerializer(serializers.ModelSerializer):: A new class TodoSerializer is created, inheriting from the ModelSerializer class of the Django REST Framework. This serializer is used to serialize and deserialize instances of the Todo model.

  4. class Meta:: This block defines Meta configurations for the serializer. In this case, the Meta class is used to specify which Django model the serializer represents and which fields should be serialized.

  5. model = models.Todo: Here, it is specified that the serializer represents the Django model Todo.

  6. fields = "__all__": This indicates that all fields of the Todo model should be included in the serializer. The option "__all__" means that all fields should be automatically included, which is convenient when you want all fields to be present in the JSON output.


Views

The example code looks like this:

from django.shortcuts import render
from rest_framework import viewsets
from . import serializers
from . import models

class TodoViewSet(viewsets.ModelViewSet):
    queryset = models.Todo.objects.all()
    serializer_class = serializers.TodoSerializer

Explanation:

Views contain the logic for retrieving, creating, updating, and deleting data. The TaskViewSet in the example uses the ModelViewSet, which inherits from viewsets.ModelViewSet. This provides pre-defined CRUD operations for the Task model.

  1. Import Statements:

    • Import necessary modules and packages such as render from django.shortcuts, viewsets from rest_framework, as well as custom serializers and models.
  2. Todo ViewSet Class:

    • Create a class named TodoViewSet that inherits from viewsets.ModelViewSet. This class is the viewset for Todo model, which means it will handle CRUD operations for instances of the Todo model.
  3. Queryset and Serializer Class:

    • In the class attributes, set the queryset to retrieve all objects from the Todo model. This queryset will be used to fetch data for various operations.
    • The serializer_class is set to your custom TodoSerializer. This serializer will be used to convert the model instances to and from a format suitable for rendering in the API.

URL’s - Backend

Add the URLs that point to the views. The router.register call automatically creates the necessary URLs for CRUD operations and associates them with the corresponding views.

The example code looks like this:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path("api/", include('todo.urls')) -> Added this line of code to the file!
]

Add URLs in the Backend:

  1. Import Statements:

    • from django.contrib import admin: This imports the Django admin module, which is a powerful tool for managing the application’s data and configurations through a web interface.

    • from django.urls import path, include: This imports the path function for defining URL patterns and the include function for including other URL patterns from different modules.

  2. URL Patterns:

    • path('admin/', admin.site.urls): This line associates the URL path ‘admin/’ with the Django admin site. When a user navigates to ‘/admin/’, they will be directed to the Django admin interface where they can manage the registered models.

    • path("api/", include('todo.urls')): This line associates the URL path ‘api/’ with the URLs defined in the ’todo.urls’ module. It uses the include function to include the URL patterns from another module (’todo.urls’).

  3. urlpatterns List:

    • The urlpatterns list is a list of URL patterns that Django will use to resolve incoming requests. Each element in the list is a call to the path function, defining a URL pattern and specifying the corresponding view or including other URL patterns.

    • In this case, there are two URL patterns:

      • The first pattern maps the ‘admin/’ path to the Django admin site.
      • The second pattern maps the ‘api/’ path to the URL patterns defined in the ’todo.urls’ module.
    • The order of the patterns matters; Django will match patterns from top to bottom, and the first match will be used.

So, when a user makes a request to ‘/admin/’ or ‘/api/’, Django will use the corresponding patterns to determine the appropriate view or include additional URL patterns for further processing.

Explanation:


URL’s - App specific

In the main application file (urls.py), create the URLs for the entire application. The router is registered here, and its URLs are included in the overall URL configuration of the application.

The example code looks like this:

from . import views
from rest_framework import routers

router = routers.DefaultRouter()
router.register("todo", views.TodoViewSet, basename="todo"  )

urlpatterns = [

]

urlpatterns += router.urls

Explanation:

This code snippet is setting up Django REST framework’s router for a viewset related to a “Todo” model. Let’s break it down step by step:

  1. Import Statements:

    • from . import views: This imports the views module from the current package (usually, it refers to the views.py file in the same directory as the current file).

    • from rest_framework import routers: This imports the routers module from Django REST framework, which provides a simple way to wire up views to a set of URLs.

  2. Router Configuration:

    • router = routers.DefaultRouter(): This creates an instance of Django REST framework’s default router. The router is used to automatically generate URL patterns for the views associated with a viewset.

    • router.register("todo", views.TodoViewSet, basename="todo"): This registers a viewset with the router. It associates the “todo” path with the TodoViewSet from the imported views module. The basename parameter is optional but can be useful for reverse URL lookups.

  3. URL Patterns List:

    • urlpatterns = []: This initializes an empty list to hold the URL patterns.

    • urlpatterns += router.urls: This appends the automatically generated URL patterns from the router to the urlpatterns list. The router.urls contains the URL patterns for the actions supported by the TodoViewSet (e.g., list, create, retrieve, update, destroy).

So, the end result is that this code sets up a Django REST framework router for a “Todo” viewset, associates it with the “todo” path, and then includes the generated URL patterns in the project’s urlpatterns. You would typically include this module’s urlpatterns in the project’s main urls.py file to make them accessible to the Django application.


Register Model in Admin.py

This step is optional and allows you to manage your database models in the Django Admin panel. By registering in admin.py, you can access and edit the data through the Admin panel.

The example code looks like this:

from django.contrib import admin
from . import models

admin.site.register(models.Todo)

Explanation:

  1. Import Statements:

    • from django.contrib import admin: This imports the admin module from Django, which provides tools for building an administrative interface.

    • from . import models: This imports the models module from the current package (likely the models.py file in the same directory). It assumes that there is a Todo model defined in the models.py file.

  2. Model Registration:

    • admin.site.register(models.Todo): This line registers the Todo model with the Django admin site. When you register a model, Django automatically creates a section in the admin interface for managing instances of that model.

    • The admin.site.register function takes the model class (models.Todo) as an argument and configures the admin interface to include it.

    • After registering the model, you can use the Django admin interface to perform various CRUD operations (Create, Read, Update, Delete) on instances of the Todo model.

Did you know?

That’s it for the Backend, next is the frontend whit React and Tailwind CSS 3.