Сбой ограничения FOREIGN KEY при создании нового пользователя
Я новичок в django и решил создать один из моих проектов, используя новые и будущие комбо реакции + django, и использую django-rest для своего бэкэнда в качестве REST API. Я построил свои модели, и все работает нормально, за исключением того, что после включения всех приведенных ниже стенок кода я пытаюсь зарегистрировать своего пользователя, но в итоге получаю ограничение внешнего ключа. Я не могу понять, что является причиной этой ошибки.
Я построил пользовательскую модель, используя django-rest-auth, в своем приложении django, которое использует django-rest-framework. Модель пользователя:
class User(AbstractBaseUser):
username = None
email = models.EmailField(_('email address'), unique=True)
name = models.CharField(max_length=100)
college = models.CharField(max_length=100)
date_of_birth = models.DateField(default=datetime.date.today)
active = models.BooleanField(default=True)
staff = models.BooleanField(default=False) # a admin user; non super-user
admin = models.BooleanField(default=False) # a superuser
is_participant = models.BooleanField(default=True)
is_mentor = models.BooleanField(default=False)
is_sponsor = models.BooleanField(default=False)
is_end_user = models.BooleanField(default=False)
contested_challenges = models.IntegerField(default=0)
mentored_challenges = models.IntegerField(default=0)
mentored_won_challenges = models.IntegerField(default=0)
sponsored_challenges = models.IntegerField(default=0)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = [ 'date_of_birth' ]
objects = UserManager()
def sponsor_challenge(self):
new_sponsor_count = self.sponsored_challenges + 1
setattr(self, 'sponsored_challenges', new_sponsor_count)
self.save(update_fields = ["sponsored_challenges"] )
def mentor_challenge(self):
new_mentor_count = self.mentored_challenges + 1
setattr(self, 'mentored_challenges', new_mentor_count)
self.save(update_fields = ["mentored_challenges"] )
def contest_challenge(self):
new_contest_count = self.contested_challenges + 1
setattr(self, 'contested_challenges', new_contest_count)
self.save(update_fields = ["contested_challenges"] )
def mentor_won_challenge(self):
new_mentor_won_count = self.mentored_won_challenges + 1
setattr(self, 'mentored_won_challenges', new_mentor_won_count)
self.save(update_fields = ["mentored_won_challenges"] )
def get_full_name(self):
# The user is identified by their email address
return self.email
def get_short_name(self):
# The user is identified by their email address
return self.email
def __str__(self): # __unicode__ on Python 2
return self.email
def has_perm(self, perm, obj=None):
"Does the user have a specific permission?"
# Simplest possible answer: Yes, always
return True
def has_module_perms(self, app_label):
"Does the user have permissions to view the app `app_label`?"
# Simplest possible answer: Yes, always
return True
@property
def is_staff(self):
"Is the user a member of staff?"
return self.staff
@property
def is_admin(self):
"Is the user a admin member?"
return self.admin
@property
def is_active(self):
"Is the user active?"
return self.active
Затем я сделал свой пользовательский менеджер пользователей, который определяется как:
class UserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, email, name, college, date_of_birth, is_participant, is_mentor, is_sponsor, is_end_user , mentored_challenges, mentored_won_challenges, sponsored_challenges, contested_challenges, password=None):
"""
Creates and saves a User with the given email and password.
"""
if not email:
raise ValueError('Users must have an email address')
user = self.model(
email=self.normalize_email(email),
date_of_birth=date_of_birth,
college=college,
name=name,
is_participant = is_participant,
is_mentor = is_mentor,
is_sponsor = is_sponsor,
is_end_user = is_end_user,
mentored_challenges = mentored_challenges,
mentored_won_challenges = mentored_won_challenges,
sponsored_challenges = sponsored_challenges,
contested_challenges = contested_challenges,
)
print(user)
user.set_password(password)
user.save(using=self._db)
return user
def create_staffuser(self, email, name, college, date_of_birth, password , is_participant, is_mentor, is_sponsor, is_end_user , mentored_challenges, mentored_won_challenges, sponsored_challenges, contested_challenges):
"""
Creates and saves a staff user with the given email and password.
"""
user = self.create_user(
email,
password=password,
date_of_birth=date_of_birth,
college=college,
name=name,
is_participant = is_participant,
is_mentor = is_mentor,
is_sponsor = is_sponsor,
is_end_user = is_end_user,
mentored_challenges = mentored_challenges,
mentored_won_challenges = mentored_won_challenges,
sponsored_challenges = sponsored_challenges,
contested_challenges = contested_challenges,
)
user.staff = True
user.save(using=self._db)
return user
def create_superuser(self, email, date_of_birth, password):
"""
Creates and saves a superuser with the given email and password.
"""
user = self.create_user(
email,
password=password,
date_of_birth=date_of_birth,
college= "True",
name= "True",
is_participant = True,
is_mentor = True,
is_sponsor = True,
is_end_user = True,
mentored_challenges = 0,
mentored_won_challenges = 0,
sponsored_challenges = 0,
contested_challenges = 0,
)
user.staff = True
user.admin = True
user.save(using=self._db)
return user
Построил мой Custom сериализатор как:
class CustomRegisterSerializer(RegisterSerializer):
email = serializers.EmailField(required=True)
password1 = serializers.CharField(write_only=True)
name = serializers.CharField(required=True)
college = serializers.CharField(required=True)
date_of_birth = serializers.DateField(required=True)
is_participant = serializers.BooleanField(default=True)
is_mentor = serializers.BooleanField(default=False)
is_sponsor = serializers.BooleanField(default=False)
is_end_user = serializers.BooleanField(default=False)
def get_cleaned_data(self):
super(CustomRegisterSerializer, self).get_cleaned_data()
return {
'password1': self.validated_data.get('password1', ''),
'email': self.validated_data.get('email', ''),
'name': self.validated_data.get('name', ''),
'college': self.validated_data.get('college', ''),
'date_of_birth': self.validated_data.get('date_of_birth', ''),
'is_participant': self.validated_data.get('is_participant',''),
'is_mentor': self.validated_data.get('is_mentor',''),
'is_sponsor': self.validated_data.get('is_sponsor',''),
'is_end_user': self.validated_data.get('is_end_user',''),
}
и, наконец, также мой собственный вид как
class CustomRegisterView(RegisterView):
queryset = User.objects.all()
У меня тогда есть мой settings.py как:
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'rest_auth',
'reset_migrations',
'problemstatements',
'faqs',
'users',
'corsheaders',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
'rest_auth.registration',
]
SITE_ID = 1
SESSION_ENGINE = "django.contrib.sessions.backends.file"
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
'rest_framework.authentication.SessionAuthentication'
)
}
ACCOUNT_USER_MODEL_USERNAME_FIELD = None
ACCOUNT_AUTHENTICATION_METHOD = 'email'
ACCOUNT_EMAIL_REQUIRED = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USERNAME_REQUIRED = False
ACCOUNT_USER_EMAIL_FIELD = 'email'
AUTH_USER_MODEL = 'users.User'
REST_AUTH_SERIALIZERS = {
"USER_DETAILS_SERIALIZER": "users.serializers.CustomUserDetailsSerializer",
}
REST_AUTH_REGISTER_SERIALIZERS = {
"REGISTER_SERIALIZER": "users.serializers.CustomRegisterSerializer",
}
Но теперь я перешел к своему / rest-auth / registration / и каждый раз, когда я пытаюсь зарегистрировать нового пользователя, я получаю сообщение об ошибке: IntegrityError в /rest-auth/registration/ FOREIGN KEY ограничение не выполняется
Traceback:
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/db/backends/base/base.py" in _commit
239. return self.connection.commit()
The above exception (FOREIGN KEY constraint failed) was the direct cause of the following exception:
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/core/handlers/exception.py" in inner
35. response = get_response(request)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
128. response = self.process_exception_by_middleware(e, request)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/core/handlers/base.py" in _get_response
126. response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/views/decorators/csrf.py" in wrapped_view
54. return view_func(*args, **kwargs)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/views/generic/base.py" in view
69. return self.dispatch(request, *args, **kwargs)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/utils/decorators.py" in _wrapper
62. return bound_func(*args, **kwargs)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/views/decorators/debug.py" in sensitive_post_parameters_wrapper
76. return view(request, *args, **kwargs)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/utils/decorators.py" in bound_func
58. return func.__get__(self, type(self))(*args2, **kwargs2)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/rest_auth/registration/views.py" in dispatch
46. return super(RegisterView, self).dispatch(*args, **kwargs)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
483. response = self.handle_exception(exc)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/rest_framework/views.py" in handle_exception
443. self.raise_uncaught_exception(exc)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/rest_framework/views.py" in dispatch
480. response = handler(request, *args, **kwargs)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/rest_framework/generics.py" in post
192. return self.create(request, *args, **kwargs)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/rest_auth/registration/views.py" in create
65. user = self.perform_create(serializer)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/rest_auth/registration/views.py" in perform_create
73. user = serializer.save(self.request)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/rest_auth/registration/serializers.py" in save
208. setup_user_email(request, user, [])
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/allauth/account/utils.py" in setup_user_email
278. a.save()
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/db/models/base.py" in save
729. force_update=force_update, update_fields=update_fields)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/db/models/base.py" in save_base
759. updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields)
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/db/transaction.py" in __exit__
212. connection.commit()
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/db/backends/base/base.py" in commit
261. self._commit()
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/db/backends/base/base.py" in _commit
239. return self.connection.commit()
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/db/utils.py" in __exit__
89. raise dj_exc_value.with_traceback(traceback) from exc_value
File "/home/tarush/virtualenvironments/api-env/lib/python3.5/site-packages/django/db/backends/base/base.py" in _commit
239. return self.connection.commit()
Exception Type: IntegrityError at /rest-auth/registration/
Exception Value: FOREIGN KEY constraint failed
Я попытался удалить все миграции, запустив их снова, и все же я не могу найти решение относительно того, что может быть причиной проблемы. Я также видел ошибки на каждом уровне в файлах Аллаута, но не могу понять, что происходит. Помогите помошь.