Reputation: 407
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.
Upvotes: 0
Views: 871
Reputation: 659
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
}
}
Upvotes: 1