Built my site and fixed some common issues

Sahil NayakSahil Nayak
5 min read

So it started from my first year of college when i thought to built my own website. Lots of ideas came to my mind the design, which tech stack blah blah.

Finally i choose Django + DRF + Mongodb initially. But yeah, that didn’t last long. MongoDB felt cool at first, but then I realized it wasn’t really the best match with Django. I mean, there were workarounds, but it just didn’t feel smooth. Also Django dont support nosql database to make you have to use djongo which is a library used to connect django and mongodb. Also it doest support ORMs properly so I dropped Mongo and switched to PostgreSQL much better integration, and Django ORMs works perfectly with sql databases.

I stuck with Django for the backend because I was already learning Python and it made sense. DRF helped me to create API super fast. For the frontend, I didn’t want to go with React like everyone else (also I didn’t like JSX that much lol), so I picked Vue.js clean and simple. Because of its SFC (Single file component) basically each .vue file content template(HTML), style(CSS), script(JS) easy to handle things. Another point is its faster than react.

I start with Backend as always (after building the logic i move to the UI part) So here in Backend part first we have to create the django project. But before creating we have to create a virtual environment for isolated environment for our project so that it doesnt clash with other libraries or other versions of same libraries. Then activate your virtual environment after doing that we are good to go. Install necessary libraries and packages including django + django rest framwork + psycopg2-binary (it works fine because it doesnt need any extra packages).

Create Django project -

django-admin startproject <name of you project> .

That dot (.) at the end means to create the project in the root directory.

Create Django apps -

python manage.py startapp <app name>

Add Those app in the installed apps inside settings.py -

    INSTALLED_APPS = [
    ...
    'portfolio', ----> web app 
    'rest_framework', ----> DRF 
]

Add then add database config in the settings.py -

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'portfolio_db', ---> db name
        'USER': 'postgres_user',  ---> postgresql username
        'PASSWORD': 'your_password', ---> postgresql user password
        'HOST': 'localhost',
        'PORT': '5432', ---> By default
    }
}

Now after adding the configuration in the settings.py we are going to work on Model creation, Views (Logic) and templates(But as we are going to use vue.js) we can skip this part.

portfolio/model.py -

from django.db import models

class Project(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()

    def __str__(self):
        return self.title ---> # This is used to show the title in the admin panel.

You can add more things according to you, after setting model.py you need to run some important things -

 python manage.py makemigrations
 python manage.py migrate

After running this you can see the table creation in your Database. So now you can create a superuser (so that you can manage everything from the admin panel inself).

python manage.py createsuperuser

So it will ask you for username, email, and password after setting them you can acces the admin panel using those credentials.

As we are using DRF we need to implement serializers so that it will convert the data into JSON format and vice versa.

from rest_framework import serializers
from .models import Project

class ProjectSerializer(serializers.ModelSerializer):
    class Meta:
        model = Project
        fields = '__all__' ---> # Include all the fields in the models

Now we are going to create views.py and setup that using DRF viewsets -

from rest_framework import viewsets
from .models import Project
from .serializers import ProjectSerializer

class ProjectViewSet(viewsets.ModelViewSet):
    queryset = Project.objects.all()
    serializer_class = ProjectSerializer

This gives you all the CRUD operations list, create, update, delete out of the box. So without implementing each operation from scratch we are just using DRF viewsets.

Setup portfolio/urls.py using DRF DefaultRouter -

from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import ProjectViewSet

router = DefaultRouter()
router.register(r'projects', ProjectViewSet)

urlpatterns = [
    path('', include(router.urls)),
]

This file registers your viewset and includes all CRUD endpoints automatically.
r'projects' means your API will look like /api/projects/

After this we need to implement the root urls in the django project - djangoproject/urls.py change the djangoproject as per your django project name.

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

urlpatterns = [
    path('admin/', admin.site.urls),
    path('api/', include('portfolio.urls')),  # Add your Django app name
]

This connects your app's URLs into the main project. so hitting /api/projects/ will now work and call the view from your app.

To run your django you need to run this command -

python manage.py runserver

After runing this it will give an url - localhost:8000 where you can access your backend. so if you write this /admin in your url then it will redirect you to the admin login page where you can login using your superuser credentials.

Some potential errors which maybe occur -

  1. Check the compartibility of Django and DRF sometimes it doesnt work so it will show error

  2. You may see error while landing on localhost:8000 because you havent created any template for root route. So you can fix that by setting up the admin login to the root route.

7
Subscribe to my newsletter

Read articles from Sahil Nayak directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sahil Nayak
Sahil Nayak