Allauth registeration request is returning 500 smallint out of range

I recently migrated my database to PostgreSQL, and up until then, everything was working fine. now when I send a registration request the server is returning the following error (Although the user is being created in the database just fine). I am getting 500 error smallint out of range although none of the posted data has integer as dataType

DataError at /authentication/registeration/
smallint out of range
Request Method: POST
Request URL:    http://127.0.0.1:8000/authentication/registeration/
Django Version: 4.0.4
Exception Type: DataError
Exception Value:    
smallint out of range
Exception Location: C:\Users\Saad\OneDrive\Documents\Scripts\python\venv\lib\site- 
packages\django\db\backends\utils.py, line 89, in _execute
Python Executable:   
C:\Users\Saad\OneDrive\Documents\Scripts\python\venv\Scripts\python.exe
Python Version: 3.10.7
Python Path:    
['C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\motanafisoun-backend',
'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310',
'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip',
'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\DLLs',
'C:\\Users\\Saad\\AppData\\Local\\Programs\\Python\\Python310\\lib',
 'C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\venv',
 'C:\\Users\\Saad\\OneDrive\\Documents\\Scripts\\python\\venv\\lib\\site-packages']
Server time:    Wed, 12 Oct 2022 13:05:57 +0300

my models.py

from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.utils.translation import gettext as _
from django.utils import timezone
from PIL import Image
from io import BytesIO
import random

GERNDER_CHOICES = (("male", "Male"), ("female", "Female"), ("unknown", "Unknown"))


class UserManager(BaseUserManager):
    use_in_migrations: True

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", False)
        extra_fields.setdefault("is_superuser", False)

        if not email:
            raise ValueError("The given email must be set")

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

    def create_superuser(self, email, password=None, **extra_fields):
        extra_fields.setdefault("is_staff", True)
        extra_fields.setdefault("is_superuser", True)
        extra_fields.setdefault("is_admin", True)
        extra_fields.setdefault("country", Country.objects.get(id=1))

        if extra_fields.get("is_staff") is not True:
            raise ValueError("Superuser must have is_staff=True.")
        if extra_fields.get("is_superuser") is not True:
            raise ValueError("Superuser must have is_superuser=True.")

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


class Country(models.Model):
    ar_name = models.CharField(max_length=100)
    ar_fullName = models.CharField(max_length=255, blank=True, null=True)
    en_name = models.CharField(max_length=100)
    iso2 = models.CharField(max_length=2,unique=True)
    iso3 = models.CharField(max_length=3,unique=True)

    def get_flag_url(self):
        return f"https://flagicons.lipis.dev/flags/4x3/{self.iso2}.svg"

    def __str__(self):
        return self.en_name

    class Meta:
        verbose_name_plural = "Countries"


class UserImage(models.Model):
    image = models.ImageField(upload_to="profile_pics")
    thumbnail = models.ImageField(
        upload_to="profile_pic-thumbnails", blank=True, null=True
    )

    def generate_thumbnail(self):
        if self.image:
            image = Image.open(self.image)
            image = image.convert("RGB")
            image.thumbnail((200, 200), Image.ANTIALIAS)
            output_io = BytesIO()
            image.save(output_io, format="JPEG")


class User(AbstractBaseUser, PermissionsMixin):
    first_name = models.CharField(max_length=25, verbose_name="First Name")
    last_name = models.CharField(max_length=25, verbose_name="Last Name")
    country = models.ForeignKey(Country, on_delete=models.CASCADE, default=1)
    email = models.EmailField(verbose_name="Email Adress", unique=True, max_length=100)

    gender = models.CharField(max_length=10, choices=GERNDER_CHOICES, default="unknown")
    birthday = models.DateField(null=True, blank=True)
    picture = models.OneToOneField(
        UserImage, on_delete=models.CASCADE, null=True, blank=True
    )

    is_active = models.BooleanField(default=True)
    is_admin = models.BooleanField(default=False)
    is_superuser = models.BooleanField(default=False)
    is_staff = models.BooleanField(default=False)
    date_joined = models.DateTimeField(default=timezone.now)

    objects = UserManager()

    USERNAME_FIELD = "email"
    REQUIRED_FIELDS = []

    def get_full_name(self):
        return f"{self.first_name} {self.last_name}"

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

    def has_module_perms(self, app_label):
        return True


class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.PROTECT)
    notifyWhenFriendOnBoard = models.BooleanField(default=True)
    notifyFriendWhenOnBoard = models.BooleanField(default=True)
    notifyWhenActionOnFigure = models.BooleanField(default=True)
    notifyWhenFriendOpenFigure = models.BooleanField(default=True)
    notifyWhenNewFigure = models.BooleanField(default=True)
    notifyWhenNewVolunteerKhotma = models.BooleanField(default=True)
    publicViewRooms = models.BooleanField(default=True)
    publicViewFriends = models.BooleanField(default=True)
    publicViewStats = models.BooleanField(default=True)

    def __str__(self):
        return self.user.email


class ActivationKeyManager(models.Manager):
    def create(self, user):
        key = random.randint(100000, 999999)
        while ActivationKey.objects.filter(key=key).exists():
            key = random.randint(100000, 999999)
        return super().create(user=user, key=key)


class ActivationKey(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name=_("user"))
    key = models.PositiveSmallIntegerField(_("key"), unique=True)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = ActivationKeyManager()


class Follow(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="following")
    following = models.ForeignKey(
        User, on_delete=models.CASCADE, related_name="followers"
    )
    # accepted=models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    class Meta:
        unique_together = ("user", "following")

settings.py


# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/


# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ["localhost","127.0.0.1","192.168.1.105","192.168.1.107"]
# ALLOWED_HOSTS = ['*']

#!#############################################################################
AUTHENTICATION_BACKENDS = [
    "django.contrib.auth.backends.ModelBackend",
    "allauth.account.auth_backends.AuthenticationBackend",
    # "authentication.backends.EmailOrUsernameModelBackend",
]
#!#############################################################################

INSTALLED_APPS = [
    "channels",
    
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    #* added
    "django.contrib.sites",
    #* local apps
    "api.apps.ApiConfig",
    "authentication.apps.AuthenticationConfig",
    "room.apps.RoomConfig",
    "khotma.apps.KhotmaConfig",
    "werd.apps.WerdConfig",
    #* third party apps
    "rest_framework",
    "rest_framework.authtoken",
    "django_extensions",
    "coreapi",
    "drf_yasg",
    "dj_rest_auth",
    "dj_rest_auth.registration",
    "allauth",
    "allauth.account",
    "allauth.socialaccount",
    "allauth.socialaccount.providers.facebook",
    "allauth.socialaccount.providers.google",
    # "allauth.socialaccount.providers.twitter",
    "debug_toolbar",
]

MIDDLEWARE = [
    "debug_toolbar.middleware.DebugToolbarMiddleware",
    
    "django.middleware.security.SecurityMiddleware",
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",
    "django.contrib.auth.middleware.AuthenticationMiddleware",
    "django.contrib.messages.middleware.MessageMiddleware",
    "django.middleware.clickjacking.XFrameOptionsMiddleware",
]

ROOT_URLCONF = "motanfisoun.urls"

TEMPLATES = [
    {
        "BACKEND": "django.template.backends.django.DjangoTemplates",
        "DIRS": [],
        "APP_DIRS": True,
        "OPTIONS": {
            "context_processors": [
                "django.template.context_processors.debug",
                "django.template.context_processors.request",
                "django.contrib.auth.context_processors.auth",
                "django.contrib.messages.context_processors.messages",
                #!
                "django.template.context_processors.request",
            ],
        },
    },
]

SITE_ID = 1

#!#############################################################################
SOICALACCOUNT_PROVIDERS = {
    "google": {
        "SCOPE": [
            "profile",
            "email",
            "openid",
            "https://www.googleapis.com/auth/user.birthday.read",
            "https://www.googleapis.com/auth/user.gender.read",
        ],
        "AUTH_PARAMS": {
            "access_type": "online",
        },
    },
    "facebook": {
        "METHOD": "oauth2",
        # "SDK_URL": "//connect.facebook.net/{locale}/sdk.js",
        "SCOPE": ["email", "public_profile"],
        "AUTH_PARAMS": {"auth_type": "reauthenticate"},
        "INIT_PARAMS": {"cookie": True},
        "FIELDS": [
            "first_name",
            "last_name",
            "name",
            "gender",
            "birthday",
            "hometown",
            "location",
            "picture",
        ],
        "APP": {
            "client_id": "396522789027356",
            "secret": "a43da8f6e534add11098c91f1c502c28",
            "key": "",
        },
        "EXCHANGE_TOKEN": True,
        # "LOCALE_FUNC": "path.to.callable",
        "VERIFIED_EMAIL": False,
        "VERSION": "v13.0",
    },
}
#!#############################################################################

WSGI_APPLICATION = "motanfisoun.wsgi.application"


DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'mutanafisun', 
        'USER': 'postgres', 
        'PASSWORD': '0959367822',
        'HOST': '127.0.0.1', 
        'PORT': '5432',
    }
}

# DATABASES = {
#     "default": {
#         "ENGINE": "django.db.backends.sqlite3",
#         "NAME": BASE_DIR / "db.sqlite3",
#     }
# }


# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",
    },
    {
        "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",
    },
    # {
    #     "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",
    # },
]


# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "Asia/Riyadh"

USE_I18N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/

STATIC_URL = "static/"

# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"


#* Custom User model Settings

AUTH_USER_MODEL = "authentication.User"
swappable_setting = "AUTH_USER_MODEL"

ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_AUTHENTICATION_METHOD = 'email'

REST_FRAMEWORK = {
    "DEFAULT_AUTHENTICATION_CLASSES": (
        "rest_framework.authentication.TokenAuthentication",
    ),
}

REST_AUTH_SERIALIZERS = {
    "USER_DETAILS_SERIALIZER": "authentication.serializers.UserDetailsSerializer",
}

REST_AUTH_REGISTER_SERIALIZERS = {
    "REGISTER_SERIALIZER": "authentication.serializers.RegisterSerializer",
    "LOGIN_SERIALIZER": "authentication.serializers.LoginSerializer",
}

#* Email Confirmation Settings

ACCOUNT_EMAIL_VERIFICATION = "optional"
EMAIL_HOST = "smtp.gmail.com"
EMAIL_PORT = 587
EMAIL_USE_TLS = True
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'  

OLD_PASSWORD_FIELD_ENABLED = True
LOGOUT_ON_PASSWORD_CHANGE = False

#* Soical Log in Settings

SOCIALACCOUNT_ADAPTER = "authentication.adapters.SocialAccountAdapter"
ACCOUNT_ADAPTER="authentication.adapters.AccountAdapter"


#* Asynchronous Server Gateway Interface (Channels settings)

ASGI_APPLICATION = "motanfisoun.asgi.application"

CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer",
        # "CONFIG": {
        #     "hosts": [("127.0.0.1", 6379)],
        # },
    },
}  

INTERNAL_IPS=['127.0.0.1']

urls.py

    path("", include("dj_rest_auth.urls")),
    path("registeration/", include("dj_rest_auth.registration.urls")),
    path("accounts/", include("allauth.urls")),
    path("email-verification/", views.VerifyUserView.as_view()),
    path("facebook/", views.FacebookLogin.as_view(), name="fb_login-url"),
    path("google/", views.GoogleLogin.as_view(), name="google_login-url"),
    path("twitter/", views.TwitterLogin.as_view(), name="twitter_login-url"),
    path("token/", authtoken_views.obtain_auth_token,name="token_auth-url"),
]
Back to Top