Register User in Django Rest Framework and Set Group For User

我的梦境 提交于 2019-12-07 05:17:37

问题


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



来源:https://stackoverflow.com/questions/20740254/register-user-in-django-rest-framework-and-set-group-for-user

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!