+2347067162698
tclassified.com@gmail.com

Gwagwalada Real Estate

Educational Technology and ICT

Created with Sketch.

Gwagwalada Real Estate

This is a real estate app for Gwagwalada in Abuja. we di this project to learn how to create an application using REST API in Django as the backend with postgres database and reactjs, a javascript framework as the front end

create a folder on the desktop ---gwagshouse
open it in vscode
create a folder called backend in the gwagshouse folder

npx create-react-app frontend

open another terminal
cd backend
check the python version you are using by doing

python --version

create a virtual environment
cd backend

python -m venv genv

navigate into the virtual environment and activate it by doing

source genv/Scripts/activate  #for windows

source gvenv/bin/activate  #for macos

pip install django djangorestframework django-cors-headers djangorestframework-simplejwt Pillow psycopg2 psycopg2-binary

set up your database

open postgr   es shell(cmd)--you make sure you downloaded and installed postgres from their official website

search and click on 
SQL Shell(psql)
put in the details to connect

server--localhost
database --postgres
port--5432
username--postgres
password--password123  or what you set as your password from initial password during postgres setup(installation)

you can set another password once presented with the postgres command prompt --- postgres=#  with the command

\password 
Enter new password: password123
Enter it again: password123

CREATE DATABASE fpl OWNER postgres;

quit the terminal and continue setup on the vscode side
\q

by now the modules installations on your backend should be complete
in your backend directory and with the virtual environment activated
put dot at the end of the command to create the django project in order to create it as the backend

django-admin startproject gwagshouse .

cd gwagshouse    

python manage.py startapp accounts

head to your settings.py under gwagshouse
fpl/backend/fpl/settings.py

import os 

INSTALLED_APPS = [

	'corsheaders',
	'rest_framework',
	'accounts',	
]


MIDDLEWARE = [
	'corsheaders.middleware.CorsMiddleware',
	
]

TEMPLATES = [
    {
        
        'DIRS': [os.path.join(BASE_DIR, 'build')],
        
    },
]


WSGI_APPLICATION = 'gwagshouse.wsgi.application'

..........................................
for sqlit3
....................................

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}
.........................
for postgres
...............................

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'realest_estate',
        'USER': 'gwagshouse',
        'PASSWORD': 'password123',
        'HOST': 'localhost'
    }
}

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = '# your email #'
EMAIL_HOST_PASSWORD = '# your app password #'
EMAIL_USE_TLS = True

we need to at some poin run 
python mange.py collect static to populate the static files at our staic root
do it as you run build when you are done with your frontend
at ht last part of settings.py

STATIC_URL = '/static/'
STATICFILES_DIRS = [
    os.path.join(BASE_DIR, 'build/static')
]
STATIC_ROOT = os.path.join(BASE_DIR, 'static')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

REST_FRAMEWORK = {
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.IsAuthenticated'
    ],
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication'
    ],
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 3
}

CORS_ORIGIN_ALLOW_ALL = True

FILE_UPLOAD_PERMISSIONS=0o640

AUTH_USER_MODEL = 'accounts.UserAccount'

try:
    from .local_settings import *
except ImportError:
    pass


....................................
fpl/backend/fpl/urls.py

from django.contrib import admin
from django.urls import path, include, re_path
from django.views.generic import TemplateView
from django.conf import settings
from django.conf.urls.static import static
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView

urlpatterns = [
    path('api-auth/', include('rest_framework.urls')),
    path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
    path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
    path('api/accounts/', include('accounts.urls')),
   
    path('admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

urlpatterns += [re_path(r'^.*', TemplateView.as_view(template_name='index.html'))]

..............................................................
fpl/backend/accounts/models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager

class UserAccountManager(BaseUserManager):
    def create_user(self, email, name, password=None):
        if not email:
            raise ValueError('Users must have an email address')
        
        email = self.normalize_email(email)
        user = self.model(email=email, name=name)

        user.set_password(password)
        user.save()

        return user
    
    def create_superuser(self, email, name, password):
        user = self.create_user(email, name, password)

        user.is_superuser = True
        user.is_staff = True
        user.save()

        return user

class UserAccount(AbstractBaseUser, PermissionsMixin):
    email = models.EmailField(max_length=255, unique=True)
    name = models.CharField(max_length=255)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)

    objects = UserAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name']

    def get_full_name(self):
        return self.name
    
    def get_short_name(self):
        return self.name
    
    def __str__(self):
        return self.email

................................................................
fpl/backend/accounts/views.py

from django.contrib.auth import get_user_model
User = get_user_model()
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import permissions

class SignupView(APIView):
    permission_classes = (permissions.AllowAny, )

    def post(self, request, format=None):
        data = self.request.data

        name = data['name']
        email = data['email']
        password = data['password']
        password2 = data['password2']

        if password == password2:
            if User.objects.filter(email=email).exists():
                return Response({'error': 'Email already exists'})
            else:
                if len(password) < 6:
                    return Response({'error': 'Password must be at least 6 characters'})
                else:
                    user = User.objects.create_user(email=email, password=password, name=name)

                    user.save()
                    return Response({'success': 'User created successfully'})
        else:
            return Response({'error': 'Passwords do not match'})


.........................................................
fpl/backend/accounts/urls.py

from django.urls import path
from .views import SignupView

urlpatterns = [
    path('signup', SignupView.as_view()),
]
....................................................

python manage.py makemigrations

python manage.py migrate

python manage.py runserver
............................................

bring in the rest from github

npm install --save react-dom react-helmet react-loader-spinner react-redux react-router-dom redux redux-devtools-extension redux-thunk uuid

const res = await axios.post(`http://localhost:8000/api/token/`, body, config);

Leave a Reply

Your email address will not be published. Required fields are marked *

Open chat