2. Create Backend
After the Main Setup we can configure our App:
Main Process
In the Django Project App:
- Models | We create a Database Model under
models.py
- Serializer | We will create the
serializer.py
file to convert complex data in JSON or other formats. - Views | We will create our View under
views.py
- URL’s - Backend | We will put the trigger under
urls.py
outside the Project App in the main Folder! - URL’s - App specific | Create URLs in the App and Register App Views and Routers
- 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:
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:
from django.db import models
: This line imports themodels
class from the Django packagedjango.db
. Django uses Object-Relational Mapping (ORM) to facilitate database interactions. Themodels
module contains classes that serve as models for database tables.class Todo(models.Model):
: Here, a new classTodo
is created, inheriting from the DjangoModel
class. By inheriting frommodels.Model
, this object becomes a Django model that is represented in the database as a table.body = models.CharField(max_length=300)
: This line defines a fieldbody
that contains the actual text of the task. It is defined as a string (CharField) with a maximum length of 300 characters.completed = models.BooleanField(default=False)
: Thiscompleted
field is a boolean field indicating whether the task is completed or not. It has a default value ofFalse
, meaning that a task is considered incomplete by default.updated = models.DateTimeField(auto_now=True)
: Theupdated
field is a DateTimeField that stores the timestamp of the last update of the task. Theauto_now=True
ensures that the field is automatically updated to the current time when the object is saved.created = models.DateTimeField(auto_now_add=True)
: Thecreated
field is also a DateTimeField that stores the timestamp of when the task was created. Theauto_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:
from rest_framework import serializers
: This line imports theserializers
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.from . import models
: Here, the localmodels
module is imported. This indicates that there is a Django app model namedTodo
in the same directory (package) as this code.class TodoSerializer(serializers.ModelSerializer):
: A new classTodoSerializer
is created, inheriting from theModelSerializer
class of the Django REST Framework. This serializer is used to serialize and deserialize instances of theTodo
model.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.model = models.Todo
: Here, it is specified that the serializer represents the Django modelTodo
.fields = "__all__"
: This indicates that all fields of theTodo
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.
Import Statements:
- Import necessary modules and packages such as
render
fromdjango.shortcuts
,viewsets
fromrest_framework
, as well as custom serializers and models.
- Import necessary modules and packages such as
Todo ViewSet Class:
- Create a class named
TodoViewSet
that inherits fromviewsets.ModelViewSet
. This class is the viewset forTodo
model, which means it will handle CRUD operations for instances of theTodo
model.
- Create a class named
Queryset and Serializer Class:
- In the class attributes, set the
queryset
to retrieve all objects from theTodo
model. This queryset will be used to fetch data for various operations. - The
serializer_class
is set to your customTodoSerializer
. This serializer will be used to convert the model instances to and from a format suitable for rendering in the API.
- In the class attributes, set the
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:
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 thepath
function for defining URL patterns and theinclude
function for including other URL patterns from different modules.
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 theinclude
function to include the URL patterns from another module (’todo.urls’).
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 thepath
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:
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.
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 theTodoViewSet
from the importedviews
module. Thebasename
parameter is optional but can be useful for reverse URL lookups.
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. Therouter.urls
contains the URL patterns for the actions supported by theTodoViewSet
(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:
Import Statements:
from django.contrib import admin
: This imports theadmin
module from Django, which provides tools for building an administrative interface.from . import models
: This imports themodels
module from the current package (likely themodels.py
file in the same directory). It assumes that there is aTodo
model defined in themodels.py
file.
Model Registration:
admin.site.register(models.Todo)
: This line registers theTodo
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.