0

I have two models:

class Group(models.Model):
    name = models.CharField(max_length=50, null=False, blank=False)

class User(models.Model):
    username = models.CharField(max_length=50, null=False, blank=False)
    password = models.CharField(max_length=50, null=False, blank=False)
    group = models.ForeignKey(Group, null=False, on_delete=models.CASCADE)

And I have serializers for both of them:

class GroupSerializer(serializers.Serializer):
    name = serializers.CharField()

class UserSerializer(serializers.Serializer):
    username = serializers.CharField()
    password = serializers.CharField()
    group = serializers.PrimaryKeyRelatedField(queryset=Group.objects.all())

Then in the registration view, I'm trying to automatically create a group when user is registering their account:

@api_view(['POST'])
def registration(request):
    # Creates a new group
    g_serializer = GroupSerializer(data=request.data, partial=True)
    g_serializer.is_valid(raise_exception=True)
    group = g_serializer.save()
    # Creates a new user
    u_serializer = UserSerializer(data=request.data, partial=True)
    u_serializer.is_valid(raise_exception=True)
    user = u_serializer.save()

As you can imagine the error I'm getting is that group field for User class violates not null restriction. I tried to fix it by doing u_serializer['group'] = group.id or u_serializer['group'] = group but it throws the following error:

TypeError: 'UserSerializer' object does not support item assignment

How can I handle this? The new Group object is being properly created and inserted into the db and I need to assign that object to user.group.

Gonzalo Dambra
  • 891
  • 2
  • 19
  • 34

1 Answers1

0

According to this https://stackoverflow.com/a/44718400/3734484 in your case would be:

...
# Creates a new user
u_serializer = UserSerializer(data=data, partial=True)
u_serializer.is_valid(raise_exception=True)
user = u_serializer.save(group=group)
...
ed_
  • 87
  • 1
  • 5
  • I appreciate your help. It's giving me the following error: AttributeError: This QueryDict instance is immutable – Gonzalo Dambra Feb 10 '20 at 23:57
  • maybe you should look at https://stackoverflow.com/a/44718400/3734484 seems more appropiate for django rest framework. I also edited the answer. – ed_ Feb 13 '20 at 00:28