I'm creating an app in django with custom registration and login that behave like forms, but when I log in with wrong credentials, the program returns an AssertionError. .
views.py
...
def post(self, request):
serializer = LoginSerializer(data=request.data)
if serializer.is_valid():
email = serializer.validated_data['email']
password = serializer.validated_data['password']
user = authenticate(email=email, password=password)
if user:
login(request, user)
return redirect('/')
else:
return Response({'erro': 'user nao encontrado'})
serializers.py
class LoginSerializer(serializers.ModelSerializer):
email = serializers.EmailField(required=True)
password = serializers.CharField(write_only=True,
style={'input_type': 'password'})
class Meta:
model = Profile
fields = ['email', 'password']
def validate(self, attrs):
email = attrs.get('email')
password = attrs.get('password')
if email and password:
user = authenticate(email=email,
password=password)
if not user:
raise serializers.ValidationError('O usuário não existe')
attrs['user'] = user
return attrs
The error in question:
AssertionError at /accounts/login/
Expected a `Response`, `HttpResponse` or `StreamingHttpResponse` to be returned from the view, but received a `<class 'NoneType'>`
I've already tried a try and except, as well as adding a Response if the user doesn't exist, but still, nothing works.
A view must always return a response. In your case there is one case where your view returns Nothing (None).
It's when serializer is not valid. I assuming that in your code all is well indented and you just make a mistake there on StackOverflow.
def post(self, request):
serializer = LoginSerializer(data=request.data)
if serializer.is_valid():
email = serializer.validated_data['email']
password = serializer.validated_data['password']
user = authenticate(email=email, password=password)
if user:
login(request, user)
return redirect('/')
else:
return Response({'erro': 'user nao encontrado'})
# When serializer.is_valid() return False, we are here, and the view ends by returning None. Django immediately raise an Assertion Error. You must add a else close here.
else:
# Return a response here.