2

I have three Django projects: Project A, Project B, and Project C. Project A serves as the authentication project, Project B is responsible for managing user-related functionalities, and Project C handles restaurant-related operations.

In Project A, I have created a custom user model to suit my authentication requirements. Now, I want to utilize this custom user model to access the APIs of both Project B and Project C.

How can I achieve this integration between the projects? Specifically, I would like to accomplish the following:

Enable user authentication: I want to use the custom user model defined in Project A to authenticate users when they access the APIs of Project B and Project C.

Share user information: I need to access user information from Project B and Project C using the custom user model defined in Project A. This includes retrieving user details, updating user profiles, and performing user-related operations.

Maintain consistency: It is essential to ensure that any changes made to the custom user model in Project A are reflected across all projects, including Project B and Project C.

Here is my Custom user Model from Project A.

import uuid

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


class UserManager(BaseUserManager):

    def _create_user(self, email, password, is_staff, is_superuser, **extra_fields):
        if not email:
            raise ValueError('Users must have an email address')
        now = timezone.now()
        email = self.normalize_email(email)
        user = self.model(
            email=email,
            is_staff=is_staff,
            is_active=True,
            is_superuser=is_superuser,
            last_login=now,
            date_joined=now,
            **extra_fields
        )
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password, **extra_fields):
        return self._create_user(email, password, False, False, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        user = self._create_user(email, password, True, True, **extra_fields)
        return user


class User(AbstractBaseUser, PermissionsMixin):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    # username = models.CharField(max_length=255, null=True, blank=True, unique=True)
    email = models.EmailField(max_length=254)
    name = models.CharField(max_length=254, null=True, blank=True)
    is_staff = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_active = models.BooleanField(default=True)
    last_login = models.DateTimeField(null=True, blank=True)
    date_joined = models.DateTimeField(auto_now_add=True)
    organization_id = models.UUIDField(null=True, blank=True)

    USERNAME_FIELD = 'email'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def get_absolute_url(self):
        return "/users/%i/" % (self.pk)

I have already tried this solution ( Using same database table with two different projects Django ). But it is not working. Or somehow I am not implemented it correctly. If this is the solution please give a full example of it.your text

1 Answers1

-1

To integrate the custom user model from Project A with Projects B and C, you can use Django's multi-database feature. This allows you to use multiple databases within a single Django project.

Here's an example of how you can achieve this integration:

  1. Define the custom user model in a separate app

To ensure consistency across all projects, it's a good practice to define the custom user model in a separate app, which can be installed and used by all three projects.

You can create a new app called "accounts" (or any other name you prefer) and define the custom user model in its models.py file.

  1. Configure the database settings for each project

In your Django settings file, you can define separate database settings for each project using Django's DATABASES configuration.

For example, you can define the database settings for Project A as follows:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'project_a_db',
        'USER': 'yourusername',
        'PASSWORD': 'yourpassword',
        'HOST': 'localhost',
        'PORT': '',
    },
}

Similarly, you can define the database settings for Projects B and C using separate database names and credentials.

  1. Define database router to route custom user model queries to Project A

To ensure that all queries related to the custom user model are routed to the Project A database, you can define a database router in a separate file, say "routers.py", inside the "accounts" app.

Here's an example of how the router can be defined:

class AccountsRouter:
    """
    A router to control all database operations on models in the
    accounts application.
    """

    def db_for_read(self, model, **hints):
        if model._meta.app_label == 'accounts':
            return 'project_a_db'
        return None

    def db_for_write(self, model, **hints):
        if model._meta.app_label == 'accounts':
            return 'project_a_db'
        return None

    def allow_relation(self, obj1, obj2, **hints):
        if obj1._meta.app_label == 'accounts' or \
                obj2._meta.app_label == 'accounts':
            return True
        return None

    def allow_migrate(self, db, app_label, model_name=None, **hints):
        if app_label == 'accounts':
            return db == 'project_a_db'
        return None

This router will ensure that all queries related to the custom user model are routed to the "project_a_db" database, while all other queries are routed to their respective databases.

  1. Set the database router in Django settings

In your Django settings file, you can set the database router to be used by all projects as follows:

DATABASE_ROUTERS = ['accounts.routers.AccountsRouter']

With these settings in place, you can now access the APIs in Projects B and C using the custom user model defined in Project A.

To authenticate users, you can use Django's authentication framework, which will automatically use the custom user model for authentication.

To share user information across projects, you can define API endpoints in Projects B and C that query the custom user model in Project A using Django's query API. For example, you can define an API endpoint in Project B to retrieve user details as follows:

from accounts.models import User

def get_user_details(request, user_id):
    user = User.objects.get(id=user_id)
    # return user details as JSON

Similarly, you can define other API endpoints to update user profiles, perform user-related operations, etc.

Kim Marry
  • 55
  • 3