我想添加用户,我正在使用django rest api模型序列化器添加用户,但是当我添加它时,它会给我:
禁止直接分配给多对多集的正面。改用user_permissions.set()。
OR
禁止直接分配给多对多集的正面。改用groups.set()。
我正在使用django AbstractBaseUser管理器,并使用了APIView和Modelerializer。
这是我的以下数据:
Models.py:
class UserManager(BaseUserManager):
def create_user(self,email,password):
user=self.model(email=email)
user.password=password
user.set_password(user.password)
user.save()
def create_staffuser(self,email,password):
user = self.model(email=email)
user.password=password
user.set_password(user.password)
# user.is_admin = True
user.is_superuser = False
user.is_staff = True
user.is_active = True
user.save()
def create_superuser(self,email,password):
user=self.model(email=email)
#user.password=password
user.set_password(password)
user.is_staff=True
user.is_superuser=True
user.save()
class User(AbstractBaseUser,PermissionsMixin):
user_image = models.CharField(max_length=100,default="new image")
# is_admin=models.BooleanField(default=False)
email = models.EmailField(unique=True)
is_staff = models.BooleanField(default=False)
first_name = models.CharField(max_length=30, blank=True)
last_name = models.CharField(max_length=30, blank=True)
date_joined = models.DateTimeField(null=True, blank=True)
username = models.CharField(
max_length=150,
unique=True,
null=True,
)
is_active = models.BooleanField(default=True)
object = UserManager()
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = []
objects = models.Manager()
def get_short_name(self):
return self.email
Serializer.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model=User
fields='__all__'
def create(self,validated_data):
user=User.objects.create(**validated_data)
return user
def update(self,instance,validated_data):
for k,v in validated_data.items():
setattr(instance,k,v)
instance.save()
return instance
Views.py
class CreateUser(APIView): # registering user on our site
def get(self,request):
return Response([UserCreateSerializer(user).data for user in User.objects.all()])
def post(self,request):
payload=request.data
serializer=UserCreateSerializer(data=payload)
if serializer.is_valid():
serializer.save()
return Response(serializer.data,status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
我已经搜索过,我猜问题出在序列化器类中的user = User.objects.create(** validated_data)上,我试图使用user.groups.set()或user.user_permission进行设置,但出现了相同的错误有人指导我寻求这种解决方案。