Django Rest Framework - 注册后返回身份验证令牌

时间:2016-06-03 20:11:36

标签: django django-rest-framework

我想在用户注册成功后在json中返回一个身份验证令牌。我怎么能这样做?

注册时我使用以下

seriazilers.py

class UserSerializer(ModelSerializer):
    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'password',
            'email',
            ]
        write_only_fields = ('password',)
        read_only_fields = ('id',)

    def create(self, validated_data):
        user = User.objects.create(
            username=validated_data['username'],
        )

        user.set_password(validated_data['password'])
        user.save()

        return user

views.py

class CreateUser(CreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = UserSerializer

2 个答案:

答案 0 :(得分:4)

当用户想要登录/登录时,这是一个简单的解决方案

首先使用pip下载 django-rest-framework-jwt

pip install djangorestframework-jwt
UserSerializer 中的

添加此项以确保用户名和密码正确(添加任意数量的字段)

username = serializers.CharField(read_only=True)
password = serializers.CharField(read_only=True)

现在在 view.py 中添加此

# authenticate: will check if the user exist
from django.contrib.auth import authenticate
# api_settings: will help generating the token
from rest_framework_jwt.settings import api_settings

def login_page(request):
    payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    encode_handler = api_settings.JWT_ENCODE_HANDLER
    serializer = UserSerializer(data=request.data)

    if serializer.is_valid():
        user = authenticate(username=request.data['username'], password=request.data['password'])
        if user:
            payload = payload_handler(user)
            token = encode_handler(payload)

            return Response({'token': token})

主要是那个!希望它有所帮助!

答案 1 :(得分:4)

有很多方法可以做到这一点。以下是现有代码的上下文示例。

from rest_framework.response import Response
from rest_framework.authtoken.models import Token
from rest_framework import status

class CreateUser(CreateAPIView):
    queryset = Profile.objects.all()
    serializer_class = UserSerializer

    def create(self, request, *args, **kwargs): # <- here i forgot self
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.perform_create(serializer)
        headers = self.get_success_headers(serializer.data)
        token, created = Token.objects.get_or_create(user=serializer.instance)
        return Response({'token': token.key}, status=status.HTTP_201_CREATED, headers=headers)