Web Application using Django. Part-1
Developing web applications is one of the most exciting jobs out there. From building simple websites, to complex applications, the sheer range of things we can do with the frameworks available is just amazing.
In this 3 part series, I will provide a systematic way to develop a Django based web-application based on the YouTube tutorial provided by Traversy Media,
https://youtube.com/playlist?list=PLillGF-RfqbbRA-CIUxlxkUpbq0IFkX60
The reason I am writing this article is because, even though they have provided an amazing tutorial, I found it a bit messy and certain issues as well, which can hamper our projects in future.
Before it all begins, we need to have some clarity as to why Django?
Django — It is a python based full-stack web development framework which enables us to develop both the back-end as well as the front-end within a single project.
Why Django? If performance and efficiency is what you are looking for with more security, then Django is the way to go. It offers better security and better performance as it has inbuilt-template house that offers quick development.
Django Rest Framework — It is a python based toolkit built on top of the Django web framework for developing Rest APIs for Django based applications. It offers a great deal of options to develop the Rest APIs according to our needs.
The main reason why Django provides for faster development of web applications, is because Django takes care of most of the recurring and trivial tasks for us. But the only downside is even though it takes care of most of these tasks, as a result it becomes more abstract and hence has a steeper learning curve.
Lets get our hands dirty now…
Part 1.
Project Work Flow.
This flow chart will help us keep track of which stage in the development cycle are we currently at.
Part 2.
Stage 1. (Installations)
Create a root folder in one of the drives and then within the folder, in the command prompt, run:
pip install pipenv
Here we are installing a virtual environment to enable us to develop a Django application within the root folder. This will make sure that whatever packages we install, they will be present locally, only within the root folder.
2. Enable the virtual environment in the root folder as:
pipenv shell
3. Then, we will install the core frameworks in the folder as:
pipenv install django djangorestframework django-rest-knox
We will install the django framework, djangorestframework and django-rest-knox. The django-rest-knox provides us with predefined endpoints for user authentication. We will see that part in the part 2 of the series.
Stage 2. (Creation of the project)
- Now in the Command Prompt, within the root folder, run:
django-admin startproject messagemanager
This will create a project folder, “messagemanager” within the root folder. You can provide any name to the project folder.
Stage 3. (Creation of Apps)
- Now, within the messagemanager folder, in the command prompt, run:
python manage.py migrate
By default Django has some of its own modules that require tables to be generated. Here, take note of “manage.py”. When we have any kind of task, be it creating apps within the project, updating the changes, running tests, etc. this “manage.py” file contains all the necessary code to execute the commands.
2. Again, within the messagemanager folder, in the command prompt, run:
python manage.py startapp messages
This will create a folder named “messages” within the project folder which acts as an app inside the project.
Refer to the diagram below:
3. Now open up the root folder in any code editor, (Atom, VS Code or any other), and you will see a folder within the messagemanager folder with the same name, i.e. “messagemanager” . This folder contains all the necessary files for the project.
4. Within this messagemanager folder, in the settings.py file, under INSTALLED_APPS, add “messages” and “rest_framework”.
This is done to make sure that the apps and necessary frameworks are connected to the project.
Stage 4. (Creation of Models)
- Within the messages folder, inside models.py file, add:
from django.db import modelsfrom django.contrib.auth.models import Userclass Message(models.Model): name = models.CharField(max_length=100) email = models.EmailField(max_length=100, unique=True) message = models.CharField(max_length=500, blank=True) created_at = models.DateTimeField(auto_now_add=True)
2. Now, before proceeding we must synchronize the database to add the model above, in the database table. So within the project folder in the Command Prompt, run:
python manage.py makemigrations messages
Here, we are making migrations in regards of messages app, but we can simply omit the “messages” in the above command and it will make the necessary migrations in all the apps within the project.
Then, to integrate the migrations, run:
python manage.py migrate
Stage 5. (Creation of Serializers)
- Inside the messages folder, create a serializers.py file and add:
from rest_framework import serializersfrom messages.models import Message# Message Serializerclass MessageSerializer(serializers.ModelSerializer): class Meta: model= Message fields = "__all__"
The serializers module of the rest_framework provides us with a very useful class, ModelSerializer. The main advantage of using ModelSerializer is that it makes our code concise. They are simply a shortcut for creating serializing classes:
- An automatically determined set of fields.
- Simple default implementations for the create() and update() methods.
Stage 6. (Creation of API Views)
- Inside the messages folder, create a file api.py and add:
from messages.models import Messagefrom rest_framework import viewsets, permissionsfrom .serializers import MessageSerializer# MessageViewsetclass MessageViewSet(viewsets.ModelViewSet): queryset = Message.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = MessageSerializer
ViewSet classes provide operations such as retrieve, or update and not method handlers such as get or put. In case of ModelViewSet, we get the complete set of default read and write operations.
Stage 7. (Creation of API Endpoints )
- In the messages folder, create a file urls.py and add:
from rest_framework import routersfrom .api import MessageViewSetrouter = routers.DefaultRouter()router.register('api/messages', MessageViewSet, 'messages')urlpatterns = router.urls
This will create the necessary API endpoint for our messages app.
2. Finally, include the messages.urls in the messagemanager folder → urls.py, under urlpatterns, as:
path('', include('messages.urls')),
Here, we are integrating our app API endpoints to our project urls.
So we come to the end of part 1. In the next part, we will see how we can add authentication to our web application.
Happy Coding!