验证用户身份并拥有登录权限后如何将其添加到组中

时间:2020-01-27 08:09:40

标签: django djoser

我已经创建了一个用户,并希望将其默认添加到查看器中的组,但前提是他已经验证了他的电子邮件ID。 我已经使用djoser创建了用于创建用户的API。在发布电子邮件已验证。现在,我不明白在验证电子邮件后如何实施添加到群组。

这是model.py

from django.db import models
from django.contrib.auth.models import AbstractUser, Group

class User(AbstractUser):

   # GROUP_CHOICES = (
    #('admin','ADMIN'),
    #('creator', 'CREATOR'),
    #('reader','READER')
    #)    
    #group = models.CharField(max_length=10, choices=GROUP_CHOICES, default='CREATOR')
    email = models.EmailField(verbose_name='email',max_length=233,unique=True)
    phone = models.CharField(null=True,max_length=255)
    is_active=models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    REQUIRED_FIELDS=['username','phone','first_name', 'last_name']
    USERNAME_FIELD = 'email'




    def get_username(self):
        return self.email

    #def add_group(self):
     #   user= User.OneToOneField(User)
     #   group = Group.objects.get(name='Creator')
     #   my_group.user_set.add(your_user)

serializer.py

class UserCreateSerializer(UserCreateSerializer):
    class Meta(UserCreateSerializer.Meta):
        model= User
        fields = ('id' ,'email', 'username' ,'password', 'first_name', 'last_name', 'phone')

应用程序中的urls.py

urlpatterns = [
    path('', include('djoser.urls')),
    path('', include('djoser.urls.authtoken')),

]

我已参考 stack overflow link 但不能将其与我的代码或如何添加代码联系起来,如果正确的话。

1 个答案:

答案 0 :(得分:1)

覆盖djoser.serializers.ActivationSerializer的一种可能方法如下-


from django.contrib.auth.models import Group
from djoser.serializers import ActivationSerializer

class MyActivationSerializer(ActivationSerializer):
    def validate(self, attrs):
        attrs = super(MyActivationSerializer, self).validate(attrs)
        group = Group.objects.get(name='your_group_name')
        self.user.groups.add(group)
        return attrs

然后在您的settings.py中更新以下内容-

DJOSER = {
    # other djoser settings
    'SERIALIZERS': {
         #other serializers

         'activation': 'your_app_name.serializers.MyActivationSerializer',

         #other serializers
    }
}