0

I'm trying to solve some of the things that don't fit me in the current django rest auth.

First of all, I would like to make it possible to sign up as a member only once I enter the password without using password2 in the rest auth.

And when I sign up as a member, the following error occurs when I insert the duplicate email.

UNIQUE constraint failed: api_user.email

How can I solve these problems? Here is my code.

models.py

from django.db import models
from django.contrib.auth.models import BaseUserManager, AbstractBaseUser, PermissionsMixin
from django.utils.translation import ugettext_lazy as _

class UserManager(BaseUserManager):
    use_in_migrations = True

    def create_user(self, email, profile, userName, password):
        user = self.model(
            email=self.normalize_email(email),
            userName=userName,
            profile=profile,
        )
        user.set_password(password)
        user.save()
        return user

    def create_superuser(self, email, password, userName, profile):
        user = self.create_user(
            email=self.normalize_email(email),
            password=password,
            userName=userName,
            profile=profile,
        )
        user.is_staff = True
        user.is_superuser = True
        user.save()
        return user

class User(AbstractBaseUser, PermissionsMixin):
    username = None
    email = models.EmailField(_('email address'), unique=True)
    userName = models.CharField(max_length=10)
    profile = models.ImageField(default='default_image.jpeg')
    is_staff = models.BooleanField(_('staff status'), default=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['userName', 'profile']

serializers.py

from .models import User
from rest_framework import serializers
from rest_auth.registration.serializers import RegisterSerializer
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer, TokenRefreshSerializer
from rest_framework_simplejwt.tokens import RefreshToken
from allauth.account import app_settings as allauth_settings
from allauth.utils import email_address_exists
from allauth.account.adapter import get_adapter
from allauth.account.utils import setup_user_email
from django.utils.translation import ugettext_lazy as _
from datetime import datetime, timedelta

class customRegisterSerializer(RegisterSerializer):
    username = None
    userName = serializers.CharField(required=True)
    profile = serializers.ImageField(use_url=True)

    def validate_email(self, email):
        email = get_adapter().clean_email(email)
        if allauth_settings.UNIQUE_EMAIL:
            if email and email_address_exists(email):
                raise serializers.ValidationError(
                    _("A user is already registered with this e-mail address."))
        return email

    def validate_password(self, password):
        return get_adapter().clean_password(password)

    def get_cleaned_data(self):
        return {
            'email': self.validated_data.get('email', ''),
            'password': self.validated_data.get('password', ''),
            'userName': self.validated_data.get('userName', ''),
            'profile': self.validated_data.get('profile', ''),
        }
    
    def save(self, request, **kwargs) :
        adapter = get_adapter()
        user = adapter.new_user(request)
        user.save()
        return user

class customTokenObtainPairSerializer(TokenObtainPairSerializer):
    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = self.get_token(self.user)
        del(data['refresh'])
        del(data['access'])
        data['token_type'] = 'bearer'
        data['access_token'] = str(refresh.access_token)
        data['expires_at'] = str(datetime.now() + timedelta(hours=6))
        data['refresh_token'] = str(refresh)
        data['refresh_token_expires_at'] = str(datetime.now() + timedelta(days=30))

        return data

class customTokenRefreshSerializer (TokenRefreshSerializer) :
    def validate(self, attrs):
        data = super().validate(attrs)
        refresh = RefreshToken(attrs['refresh'])
        del(data['refresh'])
        data['token_type'] = 'bearer'
        data['access_token'] = str(refresh.access_token)
        data['expires_at'] = str(datetime.now() + timedelta(hours=6))
        data['refresh_token'] = str(refresh)
        data['refresh_token_expires_at'] = str(datetime.now() + timedelta(days=30))

        return data

thanks in advance

leedjango
  • 411
  • 2
  • 9
  • 18

0 Answers0