#django #django-custom-user
#django #django-custom-user
Вопрос:
Я реализовал членство, создав пользовательскую модель пользователя в django rest framework. Кстати, следующая ошибка возникает при написании кода и запуске сервера.
Ошибка рекурсии: превышена максимальная глубина рекурсии при вызове объекта Python
Вот полная обратная трассировка
Traceback (most recent call last): File "D:school대회 및 프로젝트CoCovenvlibsite-packagesdjangocorehandlersexception.py", line 34, in inner
response = get_response(request) File "D:school대회 및 프로젝트CoCovenvlibsite-packagesdjangocorehandlersbase.py", line 115, in _get_response
response = self.process_exception_by_middleware(e, request) File "D:school대회 및 프로젝트CoCovenvlibsite-packagesdjangocorehandlersbase.py", line 113, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:school대회 및 프로젝트CoCovenvlibsite-packagesdjangoviewsdecoratorscsrf.py", line 54, in wrapped_view
return view_func(*args, **kwargs) File "D:school대회 및 프로젝트CoCovenvlibsite-packagesdjangoviewsgenericbase.py", line 71, in view
return self.dispatch(request, *args, **kwargs) File "D:school대회 및 프로젝트CoCovenvlibsite-packagesrest_frameworkviews.py", line 505, in dispatch
response = self.handle_exception(exc) File "D:school대회 및 프로젝트CoCovenvlibsite-packagesrest_frameworkviews.py", line 465, in handle_exception
self.raise_uncaught_exception(exc) File "D:school대회 및 프로젝트CoCovenvlibsite-packagesrest_frameworkviews.py", line 476, in raise_uncaught_exception
raise exc File "D:school대회 및 프로젝트CoCovenvlibsite-packagesrest_frameworkviews.py", line 502, in dispatch
response = handler(request, *args, **kwargs) File "D:school대회 및 프로젝트CoCoapiviews.py", line 16, in post
serializer.save() File "D:school대회 및 프로젝트CoCovenvlibsite-packagesrest_frameworkserializers.py", line 212, in save
self.instance = self.create(validated_data) File "D:school대회 및 프로젝트CoCoapiserializers.py", line 61, in create
return User.objects.create_user(**validate_data) File "D:school대회 및 프로젝트CoCoapimodels.py", line 29, in create_user
user = self.create_user( File "D:school대회 및 프로젝트CoCoapimodels.py", line 29, in create_user
user = self.create_user( File "D:school대회 및 프로젝트CoCoapimodels.py", line 29, in create_user
user = self.create_user( [Previous line repeated 951 more times] File "D:school대회 및 프로젝트CoCoapimodels.py", line 31, in create_user
email=self.normalize_email(email), File "D:school대회 및 프로젝트CoCovenvlibsite-packagesdjangocontribauthbase_user.py", line 25, in normalize_email
email_name, domain_part = email.strip().rsplit('@', 1) RecursionError: maximum recursion depth exceeded while calling a Python object [20/Aug/2020 09:55:57] "POST /auth/signUp HTTP/1.1" 500 3947748
Могу ли я узнать, как устранить эту ошибку? Вот мой код.
models.py
from django.contrib.auth.models import (BaseUserManager, AbstractBaseUser, PermissionsMixin)
from django.db import models
from django.utils import timezone
class UserManager (BaseUserManager) :
def create_user (self, username, email, profile, password=None) :
if username is None :
raise TypeError('Users should have a username')
if email is None :
raise TypeError('Users should have a email')
user = self.model(
username=username,
email=self.normalize_email(email),
profile=profile,
)
user.set_password(password)
user.save()
return user
def create_user (self, username, email, profile, password=None) :
if password is None :
raise TypeError('Password should not be none')
user = self.create_user(
username=username,
email=self.normalize_email(email),
profile=profile,
password=password
)
user.create_user(username, email, profile, password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User (AbstractBaseUser, PermissionsMixin) :
username = models.CharField(max_length=255, unique=True, db_index=True)
email = models.CharField(max_length=255, unique=True, db_index=True)
profile = models.ImageField(default='mediadefault_image.jpeg')
is_verified = models.BooleanField(default=False)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'profile']
objects = UserManager()
def __str__ (self) :
return self.email
serializers.py
from .models import User
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
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 Base64ImageField (serializers.ImageField) :
def to_internal_value (self, data) :
from django.core.files.base import ContentFile
import base64
import six
import uuid
if isinstance(data, six.string_types):
if 'data:' in data and ';base64,' in data:
header, data = data.split(';base64,')
try:
decoded_file = base64.b64decode(data)
except TypeError:
self.fail('invalid_image')
file_name = str(uuid.uuid4())[:12]
file_extension = self.get_file_extension(file_name, decoded_file)
complete_file_name = "%s.%s" % (file_name, file_extension, )
data = ContentFile(decoded_file, name=complete_file_name)
return super(Base64ImageField, self).to_internal_value(data)
def get_file_extension (self, file_name, decoded_file) :
import imghdr
extension = imghdr.what(file_name, decoded_file)
extension = "jpg" if extension == "jpeg" else extension
return extension
class customRegisterSerializer (serializers.ModelSerializer) :
password = serializers.CharField(max_length=68, min_length=6, write_only=True)
profile = Base64ImageField(use_url=True)
class Meta :
model = User
fields = ['email', 'username', 'profile', 'password']
def validate (self, attrs) :
email = attrs.get('email', '')
username = attrs.get('username', '')
profile = attrs.get('profile', '')
return attrs
def create (self, validate_data) :
return User.objects.create_user(**validate_data)
Комментарии:
1. Вы вызываете
user.create_user(....)
иself.create_user(...)
внутриcreate_user(...)
метода, что вызывает ошибку.2. вау .. так что спасибо!