class WaitingForParticipationInEventViewSet(viewsets.ModelViewSet):
queryset = WaitingForParticipationInEvent.objects.all()
serializer_class = WaitingForParticipationInEventSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer):
instance = serializer.save()
if ParticipationInEvents.objects.filter(user=instance.user, event=instance.event).exists():
print(5551)
print(ParticipationInEvents.objects.filter(user=instance.user, event=instance.event).exists())
return Response({"message": "User already in event"}, status=status.HTTP_400_BAD_REQUEST)
else:
waiting_serializer = WaitingForParticipationInEventSerializer(data={'url': instance.url, 'id': instance.id, 'username': instance.username,'first_name': instance.first_name, 'read': instance.read, 'user': instance.user, 'event': instance.event})
if waiting_serializer.is_valid():
waiting_serializer.save()
print(555)
return Response({"detail": "Допущено: Объект успешно создан в ModelA."}, status=status.HTTP_201_CREATED)
return Response(waiting_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
There is my model viewset, when I am creating WaitingForParticipationInEvent object I need to check an existence of ParticipationInEvents object with the same user and event, if exists I return bad request, if does not I create the object. Butyour text it does not return bad requеst though print(5551) works. Help pls
>Solution :
The issue you’re facing seems to be related to the control flow of your perform_create method in your viewset. Specifically, you’re trying to return a response directly from the perform_create method, which is not the intended way to handle such cases in Django REST Framework.
The perform_create method is meant for performing any additional actions after creating an instance, but it’s not directly responsible for returning the HTTP response. Instead, you should raise an exception if the condition is not met, and then let Django REST Framework’s exception handling process return the appropriate HTTP response.
Here’s how you can modify your code to achieve the desired behavior:
from rest_framework.exceptions import ValidationError
class WaitingForParticipationInEventViewSet(ModelViewSet):
queryset = WaitingForParticipationInEvent.objects.all()
serializer_class = WaitingForParticipationInEventSerializer
permission_classes = [permissions.IsAuthenticated]
def perform_create(self, serializer):
instance = serializer.save()
if ParticipationInEvents.objects.filter(user=instance.user, event=instance.event).exists():
raise ValidationError("User already in event")
else:
waiting_serializer = WaitingForParticipationInEventSerializer(
data={
'url': instance.url,
'id': instance.id,
'username': instance.username,
'first_name': instance.first_name,
'read': instance.read,
'user': instance.user,
'event': instance.event
}
)
if waiting_serializer.is_valid():
waiting_serializer.save()
else:
raise ValidationError(waiting_serializer.errors)
In this modified version:
-
We’re raising a ValidationError exception when the condition is not met, which will be caught by Django REST Framework’s exception handling and converted into an appropriate HTTP response with a status of 400 Bad Request.
-
If the condition is met and the serializer is valid, we save the instance using the waiting_serializer.
-
If there are any issues with the serializer’s validity, we raise a ValidationError with the serializer’s errors, which will also be converted into an appropriate HTTP response.
By raising exceptions, you allow Django REST Framework to handle the response generation and error handling in a more standardized way.