codingforentrepreneurs / Blog-API-with-Django-Rest-Framework

Blog API with Django Rest Framework
MIT License
356 stars 173 forks source link

Is the login function incomplete? #4

Open Ru7z opened 7 years ago

Ru7z commented 7 years ago

Hi, i am an audience from Youtube.When i was learning this course, i found some questions.

Thanks for the courses, i learned a lot from it. Waiting for your replay.

Ru7z commented 7 years ago
from django.contrib.auth import (
    get_user_model,
    login,
    authenticate)

# ...

def post(self, request, *args, **kwargs):
    data = request.data
    username = data.get('username')
    password = data.get('password')
    user = authenticate(username=username, password=password)
    if user is not None and user.is_active:
        login(request, user)
        serializer = UserLoginSerializer(data=data)
        if serializer.is_valid(raise_exception=True):
            new_data = serializer.data
            return Response(new_data, status=HTTP_200_OK)
        return Response(serializer.errors, status=HTTP_400_BAD_REQUEST)
    return Response('password error', HTTP_400_BAD_REQUEST)