Я хочу иметь возможность присоединить пользователя к группе при создании.
Вот результат выбора * из auth_group:
снимок экрана
Вот мой файл serializer.py:
from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta(object):
model = User
fields = ('id', 'email', 'first_name', 'last_name', 'phone', 'address', 'is_active', 'is_staff',
'is_superuser', 'date_joined', 'password',)
extra_kwargs = {'password': {'write_only': True}}
Вот мой файл model.py:
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin, UserManager, Group
from django.db import models, transaction
# Create your models here.
from django.utils import timezone
class UserManager(BaseUserManager):
def _create_user(self, email, password, **extra_fields):
"""
Creates and saves a User with the given email,and password.
"""
if not email:
raise ValueError('User must have an email address')
email = self.normalize_email(email)
if not extra_fields["group_id"]:
raise ValueError('User must have group id')
try:
with transaction.atomic():
user = self.model(email=email, **extra_fields)
group = Group.objects.get(extra_fields["group_id"])
group.user_set.add(user)
user.set_password(password)
user.save(using=self._db)
return user
except:
raise
def create_user(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', False)
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_staff', True)
extra_fields.setdefault('is_superuser', True)
return self._create_user(email, password=password, **extra_fields)
class User(AbstractBaseUser, PermissionsMixin):
"""
An abstract base class implementing a fully featured User model with
admin-compliant permissions.
"""
email = models.EmailField(max_length=40, unique=True)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
phone = models.CharField(max_length=20, blank=True)
address = models.CharField(max_length=30, blank=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
date_joined = models.DateTimeField(default=timezone.now)
objects = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name', 'phone']
def get_full_name(self):
"""" Used to display user's full name """
return "{}, {}".format(self.first_name, self.last_name)
def __srt__(self):
return self.email
def save(self, *args, **kwargs):
super(User, self).save(*args, **kwargs)
return self
И, наконец, вот мой view.py:
class CreateUserAPIView(APIView):
# Allow any user (authenticated or not) to access this url
permission_classes = (AllowAny,)
def post(self, request):
user = request.data
serializer = UserSerializer(data=user)
serializer.is_valid(raise_exception=True)
serializer.save()
return Response({"user": serializer.data, "status": status.HTTP_200_OK})
Я хочу для этого запроса:
{
"email": "myemail@gmail.com",
"first_name": "myfirst_name",
"last_name": "mylast_name",
"phone": "000556660",
"address": "myaddress",
"password": "mypassword",
"group_id": 5
}
Чтобы получить этот ответ:
{
"status": 200,
user: {
"email": "myemail@gmail.com",
"first_name": "myfirst_name",
"last_name": "mylast_name",
"phone": "000556660",
"address": "myaddress",
"password": "mypassword",
"groups": [5]
}
}
Я перешел по этой ссылке Добавление пользователя в группу в django , но это не помогает мне.
Спасибо, любая помощь будет оценена.