注册Djoser,django-rest-framework-jwt和django-rest-framework后获取令牌

时间:2017-01-11 19:08:28

标签: python django django-rest-framework

我试图在用户注册后获取令牌,但我不能。 我读了这个post和这个doc,但我没有得到它。我也尝试过这样的事情UserRegistrationSerializer,但它仍然没有工作。我发现了这个issue,但我想我不明白我该做什么。

这是我的models.py:

from __future__ import unicode_literals

from django.db import models
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _

from .managers import UserManager


class User(AbstractBaseUser, PermissionsMixin):
    created = models.DateTimeField(_('created'), auto_now_add=True)
    email = models.EmailField(_('email'), unique=True, blank=False)
    name = models.CharField(_('name'), max_length=30, blank=False)
    last_name = models.CharField(_('last name'), max_length=100, blank=False)
    is_active = models.BooleanField(_('active'), default=True)
    birthday = models.CharField(_('birthday'), max_length=15, blank=False)

    objects = UserManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['name', 'last_name', 'birthday']

    class Meta:
        ordering = ('created',)
        verbose_name = _('user')
        verbose_name_plural = _('users')

    def get_full_name(self):
        """
        Returns the first_name plus the last_name, with a space in between.
        """
        full_name = '%s %s' % (self.first_name, self.last_name)
        return full_name.strip()

    def get_short_name(self):
        """
        Returns the short name for the user.
        """
        return self.name

my managers.py

from django.contrib.auth.base_user import BaseUserManager


class UserManager(BaseUserManager):
    use_in_migrations = True

    def _create_user(self, email, password, **extra_fields):
        """
        Creates and saves a User with the given email and password.
        """
        if not email:
            raise ValueError('The given email must be set')
        email = self.normalize_email(email)
        user = self.model(email=email, **extra_fields)
        user.set_password(password)
        user.save(using=self._db)
        return user

    def create_user(self, email, password=None, **extra_fields):
        extra_fields.setdefault('is_superuser', False)
        return self._create_user(email, password, **extra_fields)

    def create_superuser(self, email, password, **extra_fields):
        extra_fields.setdefault('is_superuser', True)

        if extra_fields.get('is_superuser') is not True:
            raise ValueError('Superuser must have is_superuser=True.')

        return self._create_user(email, password, **extra_fields)

我的serializers.py

from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from users.models import User


class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ('url', 'id', 'email', 'name', 'last_name', 'birthday')

    def create(self, request, *args, **kwargs):
        # if settings.get('SEND_ACTIVATION_EMAIL'):
        #     with transaction.atomic():
        #         user = User.objects.create_user(**validated_data)
        #         user.is_active = False
        #         user.save(update_fields=['is_active'])
        # else:
        user = User.objects.create_user()
        token = create_token(user)
        return {user, token}


def create_token(user):
    jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
    jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER

    payload = jwt_payload_handler(user)
    token = jwt_encode_handler(payload)

    return token.decode('unicode_scape')

我的应用网址:

from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter

from .views import UserViewSet

router = DefaultRouter()
router.register(r'users', UserViewSet)

urlpatterns = [
    url(r'^', include(router.urls)),
]

和我的views.py

from rest_framework import viewsets
from rest_framework_jwt.settings import api_settings

from users.models import User
from users.serializers import UserSerializer


class UserViewSet(viewsets.ModelViewSet):
    queryset = User.objects.all()
    serializer_class = UserSerializer

我对这一切都很陌生,我真的不知道自己做错了什么。 我希望有人能帮帮忙。

1 个答案:

答案 0 :(得分:3)

我找到了答案。

重点是我必须覆盖djoser的RegistrationView。

所以,我写了这个观点:

class RegistrationView(viewsets.ModelViewSet):
    queryset = User.objects.all()  # I don't know what to write here :D
    serializer_class = UserRegistrationSerializer

    permission_classes = (
        permissions.AllowAny,
    )

    def perform_create(self, serializer):
        user = serializer.save()
        signals.user_registered.send(sender=self.__class__, user=user, request=self.request)
        if settings.get('SEND_ACTIVATION_EMAIL'):
            self.send_activation_email(user)
        elif settings.get('SEND_CONFIRMATION_EMAIL'):
            self.send_confirmation_email(user)

    def create(self, request, *args, **kwargs):
        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 = create_token(serializer.data)
        return Response(data=token, status=status.HTTP_201_CREATED, headers=headers)

    def send_activation_email(self, user):
        email_factory = utils.UserActivationEmailFactory.from_request(self.request, user=user)
        email = email_factory.create()
        email.send()

    def send_confirmation_email(self, user):
        email_factory = utils.UserConfirmationEmailFactory.from_request(self.request, user=user)
        email = email_factory.create()
        email.send()

然后在网址中我要说它应该采纳我的观点。就是这样。