Показывает пользовательские сообщения об ошибках, но не показывает ошибку, которую я определил DRF
Я создаю регистрационный API с помощью DRF, но получаю пользовательское сообщение об ошибке типа "Пользователь с таким email уже существует"
Пожалуйста, прочитайте приведенный ниже код
View.py
from rest_framework import generics
from rest_framework import status
from rest_framework.permissions import AllowAny
from .serializers import RegisterSerializer
from projectname.utils import custom_response
class RegisterView(generics.CreateAPIView):
serializer_class = RegisterSerializer
permission_classes = [AllowAny]
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
user = serializer.save()
response_data = {
"username": user.username,
"first_name": user.first_name,
"last_name": user.last_name,
"email": user.email,
"user_type": user.user_type,
}
return custom_response(
success=True,
message="User registered successfully",
data=response_data,
status_code=status.HTTP_201_CREATED
)
else:
return custom_response(
success=False,
message="User registration failed",
errors={"error_message": list(serializer.errors.values())},
status_code=status.HTTP_400_BAD_REQUEST
)
serializer.py
from rest_framework import serializers
from .models import CustomUser
class RegisterSerializer(serializers.ModelSerializer):
password = serializers.CharField(write_only=True)
class Meta:
model = CustomUser
fields = ('email', 'username', 'first_name', 'last_name', 'user_type', 'password')
def validate(self, data):
required_fields = ['email', 'username', 'first_name', 'last_name', 'user_type', 'password']
errors = {}
for field in required_fields:
if field not in data or not data[field].strip():
errors[field] = f"{field.replace('_', ' ').capitalize()} is required."
if CustomUser.objects.filter(email=data.get('email', '')).exists():
errors['error_message'] = "Email already exists."
if CustomUser.objects.filter(username=data.get('username', '')).exists():
errors['error_message'] = "Username already exists."
if errors:
raise serializers.ValidationError({"error_message": list(errors.values())})
return data
def create(self, validated_data):
user = CustomUser.objects.create_user(
email=validated_data['email'],
username=validated_data['username'],
first_name=validated_data['first_name'],
last_name=validated_data['last_name'],
user_type=validated_data['user_type'],
password=validated_data['password']
)
return user
models.py
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
class CustomUserManager(BaseUserManager):
def create_user(self, email, username, first_name, last_name, user_type, password=None):
if not email:
raise ValueError('The Email field must be set')
email = self.normalize_email(email)
user = self.model(email=email, username=username, first_name=first_name, last_name=last_name, user_type=user_type)
user.set_password(password)
user.save(using=self._db)
return user
def create_superuser(self, email, username, password=None):
user = self.create_user(email, username, password)
user.is_admin = True
user.is_staff = True
user.is_superuser = True
user.save(using=self._db)
return user
class CustomUser(AbstractBaseUser, PermissionsMixin):
USER_TYPE_CHOICES = (
('child', 'Child'),
('parent', 'Parent'),
('admin', 'Admin'),
)
email = models.EmailField(unique=True)
username = models.CharField(max_length=30, unique=True)
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)
user_type = models.CharField(max_length=10, choices=USER_TYPE_CHOICES)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
objects = CustomUserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username', 'first_name', 'last_name', 'user_type']
def __str__(self):
return self.email
ответ
{
"status_code": 400,
"status": false,
"message": "User registration failed",
"data": null,
"errors": {
"error_message": [
[
"custom user with this email already exists."
],
[
"custom user with this username already exists."
]
]
}
}
здесь я хочу показать ответ как
- Электронная почта уже занята
- Имя пользователя уже занято
но я не знаю, почему я не получаю вышеуказанную ошибку, пожалуйста, дайте мне знать причину, я буду очень благодарен вам
Вам нужно обновить ошибки обоих полей следующим образом
serializers.py
class YourSerializer(serializers.Serializer): # Replace with your serializer class
def validate(self, data):
required_fields = ['email', 'username', 'first_name', 'last_name', 'user_type', 'password']
errors = {}
# Check required fields
for field in required_fields:
if field not in data or not data[field].strip():
errors[field] = f"{field.replace('_', ' ').capitalize()} is required."
# Check if email already exists
if 'email' in data:
if CustomUser.objects.filter(email=data['email']).exists():
errors['email'] = "Email already exists."
# Check if username already exists
if 'username' in data:
if CustomUser.objects.filter(username=data['username']).exists():
errors['username'] = "Username already exists."
# Raise validation error if any errors found
if errors:
raise serializers.ValidationError(errors)
return data