My Journey on how I built an online marketplace api (Part 1)

·

3 min read

For this project, I used Django to build the models, Django rest framework for the API, and MySQL for the database.

What are the steps needed to proceed

create a virtualenv using pipenv and activate it

Desktop/Development/: pip install pipenv
Desktop/Development/: pipenv shell #this activates the environment

Install the Django project using this command

Desktop/Development/: pip install django

install Django rest framework

Desktop/Development/:pip install django_rest_framework

Create a project and change the directory to the folder

Desktop/Development/:django-admin startproject marketplace
Desktop/Development/: cd marketplace

Afterward, I created an application for the project

Desktop/Development/marketplace/: python manage.py startapp product

It is a good practice to create a custom user before we start working on our project. So let's create a custom user, we'll create another app to manage the accounts.

Desktop/Development/marketplace/: python manage.py startapp accounts

Then I included the newly created app in my Django project settings and also the installed django_rest_framework

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

    #projects app
    'accounts.apps.AccountsConfig',    
    'product.apps.ProductConfig',    
    #third party app
    'rest_framework'
]

Go to the product folder and select the model file and enter the code

from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
# Create your models here.

User = settings.AUTH_USER_MODEL

class Product(models.Model):
    STATUS = (
        ("Available", "Available"),
        ("Uavailable", "Unavailable")
    )
    user = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name='user')
    name = models.CharField(_('Enter product name'), max_length=100)
    image = models.ImageField(upload_to='media/product')
    price = models.DecimalField(max_digits=8, decimal_places=2, default=0)
    quantity = models.IntegerField(default=0)
    stock = models.CharField(choices=STATUS, default='available', max_length=100)
    category = models.ForeignKey(Category, on_delete=models.PROTECT, related_name='products',
                                 null=True,
                                 blank=True)
    description = models.TextField()
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        indexes = [ 
            models.Index(fields=['-created'])
        ]
        ordering = ['-created']

    def __str__(self):
        return self.name

Go to the accounts folder, select the models.py file and enter the code

from django.db import models
from django.contrib.auth.models import (
    BaseUserManager,
    AbstractBaseUser
)

class UserManager(BaseUserManager):
    def create_user(self, username, email, password=None):
        if not email:
            raise ValueError('Email must be provided')

        if not username:
            raise ValueError('Username must be provided')

        user = self.model(
            email = self.normalize_email(email),
            username=username
        )
        user.set_password(password)
        user.save(using=self._db)
        return user


    def create_superuser(self, username, email, password):
        user = self.create_user(
            username,
            email,
            password=password
        )
        user.staff = True
        user.admin = True
        user.save(using=self._db)
        return user
  from django.db import models
  from django.contrib.auth.models import (
      BaseUserManager,
      AbstractBaseUser
  )

  class UserManager(BaseUserManager):
      def create_user(self, username, email, password=None):
          if not email:
              raise ValueError('Email must be provided')

          if not username:
              raise ValueError('Username must be provided')

          user = self.model(
              email = self.normalize_email(email),
              username=username
          )
          user.set_password(password)
          user.save(using=self._db)
          return user


      def create_superuser(self, username, email, password):
          user = self.create_user(
              username,
              email,
              password=password
          )
          user.staff = True
          user.admin = True
          user.save(using=self._db)
          return user
class User(AbstractBaseUser):
    USER_ROLES = (
        ("Seller", "Seller"),
        ("buyer", "buyer"),
    )
    username = models.CharField(max_length=30, unique=True)
    first_name = models.CharField(max_length=40)
    last_name = models.CharField(max_length=30)
    email = models.EmailField(verbose_name='Email Address',
                              unique=True,
                              max_length=40)
    active = models.BooleanField(default=True)
    admin = models.BooleanField(default=False)
    staff = models.BooleanField(default=False)
    role = models.CharField(choices=USER_ROLES, max_length=100, default='seller')
    USERNAME_FIELD = 'username'
    REQUIRED_FIELDS = ['email']


    objects = UserManager()
    def get_full_name(self):
        return f'{self.first_name} {self.last_name}'

    def get_short_name(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return True    

    def has_module_perms(self, app_label):
        return True   

    @property
    def is_staff(self):
        return self.staff

    @property
    def is_admin(self):
        return self.admin

let's create the database using MySQL, but you need to install the mysql client for this to work.

create database store;
use store;

configure the project to use MySQL

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'store',
        'USER': 'enter your username',
        'PASSWORD': 'enter your password',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}

if you are having a problem with setting up MySQL, you can just use the default database on Django which is SQLite

Now let's run the migration on the project

Desktop/Development/marketplace/: python manage.py makemigrations
Desktop/Development/marketplace/: python manage.py migrate

let create superuser

Desktop/Development/marketplace/: python manage.py createsuperuser

fill in the necessary parts

Then run the server

Desktop/Development/marketplace/: python manage.py runserver

I'll be ending the guide here, the next step would be coming up soon

What do you think about it so far? please let me know below.