0

I have created a user and want to add him to groups by default viewer but only when he has verified his email id. I have used djoser to create the APIs to create user. On post email is verified . Now I cant understand how to implement adding to group when email is verified.

this is 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 in the app

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

]

I have refereed to stack overflow link but cant relate it to my code or how to add it, if its the right way.

Sourav Roy
  • 347
  • 3
  • 20
  • Where are you verifying the email? – alamshafi2263 Jan 27 '20 at 08:34
  • djoser will send token to the email . I need to post the token to activate it. If its possible to add to group without verification that will also do.. I believe I am making it too complex for myself.. – Sourav Roy Jan 27 '20 at 08:42
  • In that case override the djoser `User Activate` endpoint or extend `djoser.serializers.ActivationSerializer` and write your custom logic there. – alamshafi2263 Jan 27 '20 at 09:15

1 Answers1

1

One possible way by overriding djoser.serializers.ActivationSerializer would be as follows -


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

Then in your settings.py update the following -

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

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

         #other serializers
    }
}

alamshafi2263
  • 639
  • 4
  • 15