Register User in Django Rest Framework and Set Gro

2019-05-05 05:09发布

问题:

My user class is:

class UserProfile(User):
    sex = models.SmallIntegerField(verbose_name=_(u'sex'), choices=SEX_TYPES, default=1)
    .
    .

UserProfileSerializer:

class ProfileSerializer(serializers.ModelSerializer):
     groups = GroupSerializer()

     class Meta:
        model = UserProfile
        fields = ('id', 'first_name', 'last_name', 'username','email','groups')

Api view that allow users to register is:

@api_view(['POST'])
def create_user(request):
      serialized = ProfileSerializer(data=request.DATA)
      if serialized.is_valid():
          created_user = UserProfile.objects.create_user(
              serialized.init_data['email'],
              serialized.init_data['username'],
              serialized.init_data['password'],
          )
          # here I want assign a group for user or anything else
          created_user.groups = "users"
          created_user.save()

          return Response(serialized.data, status=status.HTTP_201_CREATED)
      else:
          return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST)

with this test:

curl -X POST -H "Content-Type: application/json" -d '
{
"username":  "aaa",
"email": "aa@aaa.com" ,
"password":  "111111"
}' http://127.0.0.1:8000/api/users/register/

There is always error with groups.{"groups": ["This field is required."]}

How can I assign a group for user or anything else?

Thanks in advance

回答1:

Make sure you have users group created, then you do the following:

from django.contrib.auth.models import Group

users_group = Group.objects.get(name='users')

created_user.groups = [users_group]
# or instead:
# created_user.groups.add(users_group)

Reference:

https://docs.djangoproject.com/en/dev/topics/auth/default/#permissions-and-authorization