Ограничение Django FOREIGN KEY не работает при регистрации новых пользователей
Я сталкиваюсь с ошибкой "FOREIGN KEY constraint failed" при попытке зарегистрировать новых пользователей в моем Django приложении. Вот соответствующий код из моих файлов models.py, serializers.py и views.py:
Serializers.py:
User = get_user_model()
class UserSerializer(serializers.ModelSerializer):
friends = serializers.SerializerMethodField()
class Meta:
model = User
fields = ['id', 'name', 'email', 'date', 'password', 'profile_picture', 'friends']
extra_kwargs = {'password': {'write_only': True, 'required': True}}
def get_friends(self, obj):
friends = obj.get_friends() # Assuming get_friends returns a list of friend objects
return friends if friends else [] # Return empty list if friends is empty
@transaction.atomic
def create(self, validated_data):
print("User Serializer create()")
print("Validated data: ", validated_data)
user = User.objects.create_user(**validated_data)
print("User before tokenization ", user.__dict__)
print("User created, about to tokenize")
# Check if user is saved in the database
try:
user_check = User.objects.get(email=user.email)
print("User saved in database: ", user_check.__dict__)
except User.DoesNotExist:
print("User not found in database")
raise serializers.ValidationError({"error": "User not saved in database"})
try:
token, created = Token.objects.get_or_create(user=user)
if created:
print("Token created: ", token.key)
else:
print("Token already exists for user: ", token.key)
print("User and Token creation successful")
# Ensuring transaction is committed
transaction.on_commit(lambda: print("Transaction committed successfully"))
return user
except Exception as e:
print("Error during token creation: ", str(e))
raise serializers.ValidationError({"error": "Token creation failed"})
views.py
class UserView(APIView):
def post(self, request):
print(request.data)
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
print("serializer is valid")
try:
user = serializer.save()
token = Token.objects.get(user=user)
print("Token retrieved: ", token.key)
response_data = {
'token': token.key,
'user': UserSerializer(user).data # Return user data if needed
}
return Response(data=response_data, status=status.HTTP_201_CREATED)
except Exception as e:
print("Error during response handling: ", str(e))
return Response(data={'error': 'Internal Server Error'}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
else:
print("serializer is not valid")
print(serializer.errors)
return Response(data=serializer.errors, status=status.HTTP_400_BAD_REQUEST)
models.py
class UserManager(BaseUserManager):
use_in_migrations = True
def create_user(self, name, email, password=None):
print("User Manager create_user()")
if not email:
raise ValueError('Users must have an email address')
if not name:
raise ValueError('Users must have names')
email = self.normalize_email(email)
name = name.strip()
user = self.model(name=name, email=email)
user.set_password(password)
print("User before save: ", user.__dict__) # Print user details before save
user.save(using=self._db)
print("User after save: ", user.__dict__) # Print user details after save
# Query the database for the user
try:
user_in_db = User.objects.get(email=email)
print("User found in database: ", user_in_db.email)
except User.DoesNotExist:
print("User does not exist in database")
return user
class User(AbstractBaseUser):
name = models.CharField(max_length=255)
email = models.EmailField(max_length=255, unique=True)
date = models.DateTimeField(auto_now_add=True)
profile_picture = models.ImageField(upload_to='profile_pictures/', null=True, blank=True)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['name']
objects = UserManager()
def get_friends(self):
return [friendship.friend for friendship in self.friend_set.all()]
def get_followed_bars(self):
return [follow.bar for follow in self.following_set.all()]
def __str__(self):
return self.email
Вот вывод отладочного оператора печати:
{'name':
'пример пользователя', 'email': 'example@user.com', 'password': 'пароль'} сериализатор действителен Сериализатор пользователя create() Проверенные данные: { 'name': 'example user', 'email': 'example@user.com', 'password': 'password'} Менеджер пользователей create_user() Пользователь перед сохранением: {'_state': <django.db.models.base.ModelState object at 0x000001D551313D10>, 'id': None, 'password': 'pbkdf2_sha256$720000$3Meryh67k59Mt15lsIkNpP$tL/wSUPvGoCT00OUv04rO8FQI9OoO1gvgcU7qncRkgA=', 'last_login': None, 'name': 'example user', 'email': 'example@user.com', 'date': Нет, 'profile_picture': Нет, '_пароль': 'password'} Пользователь после сохранения: {'_state': <django.db.models.base.ModelState object at 0x000001D551313D10>, 'id': 1, 'password': 'pbkdf2_sha256$720000$3Meryh67k59Mt15lsIkNpP$tL/wSUPvGoCT00OUv04rO8FQI9OoO1gvgcU7qncRkgA=', 'last_login': None, 'name': 'example user', 'email': 'example@user.com', 'date': datetime.datetime(2024, 7, 8, 19, 44, 45, 577140, tzinfo=datetime.timezone.utc), 'profile_picture': <ImageFieldFile: None>, '_password': None} Пользователь найден в базе данных: example@user.com Пользователь до токенизации {'_state': <django.db.models.base.ModelState object at 0x000001D551313D10>, 'id': 1, 'password': 'pbkdf2_sha256$720000$3Meryh67k59Mt15lsIkNpP$tL/wSUPvGoCT00OUv04rO8FQI9OoO1gvgcU7qncRkgA=', 'last_login': None, 'name': 'пример пользователя', 'email': 'example@user.com', 'date': datetime.datetime(2024, 7, 8, 19, 44, 45, 577140, tzinfo=datetime.timezone.utc), 'profile_picture': <Im