Reputation: 582
I have a generic class based view and I am trying to return a response based on some conditions but it is not happening.
# Create your views here.
class UserViewCreate(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
response = HttpResponse('')
def perform_create(self, serializer):
if serializer.is_valid():
if self.check_signin_details(self.request.data):
serializer.save()
self.response.status_code = 201
self.response["message"] = "User created successfully."
return self.response
else:
self.response.status_code = 400
self.response["message"] = "Password or username policy failed."
return self.response
@staticmethod
def check_signin_details(data):
return len(data['username']) < 11 and len(data['userpassword']) > 10
I expect the response and status_code which I am setting. But I am getting a 201 everytime even on else case. Simply put, I am not getting the custom resposne.
Upvotes: 1
Views: 2290
Reputation: 88499
Override create()
method of your view,
from rest_framework.response import Response
class UserViewCreate(generics.CreateAPIView):
queryset = User.objects.all()
serializer_class = UserSerializer
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
serializer.is_valid(raise_exception=True)
if self.check_signin_details(self.request.data):
self.perform_create(serializer)
return Response(data={"message": "User created successfully."}, status=status.HTTP_201_CREATED)
return Response(data={"message": "Password or username policy failed."}, status=status.HTTP_400_BAD_REQUEST)
@staticmethod
def check_signin_details(data):
return len(data['username']) < 11 and len(data['userpassword']) < 10
I removed perform_create()
method from your view, it's irrelevent here, becase, it will save the instance only if your custom username/password policy passed
Upvotes: 4
Reputation: 47354
perform_create
doesn't return http response (see source). It just saving object. You should override create
method if you need to modify response:
def create(self, request, *args, **kwargs):
serializer = self.get_serializer(data=request.data)
if serializer.is_valid():
if self.check_signin_details(self.request.data):
serializer.save()
self.response.status_code = 201
self.response["message"] = "User created successfully."
return self.response
else:
self.response.status_code = 400
self.response["message"] = "Password or username policy failed."
return self.response
Upvotes: 2