How to create a user for a profile in the django API

0

I have this in this serializer:

class ProfileSerializer(serializers.HyperlinkedModelSerializer):
   shops = ShopListingField(read_only=False, required=False)
   publishers = PublisherListingField(read_only=False, required=False)
   profile_types = ProfileTypeListingField(read_only=False, required=False)
   cooperative_universes = CooperativeUniverseListingField(read_only=False, required=False)
   countries = CountryListingField(read_only=False, required=False)
   language = LanguageField(read_only=False, required=False, queryset=Language.objects.all())
   username = UserField(read_only=False, required=True, queryset=User.objects.all())

The UserField is:

class UserField(serializers.RelatedField):

  def to_representation(self, value):
      return value.username

  def to_internal_value(self, data):
      user_found = User.objects.filter(username=data)
      if user_found:
          raise serializers.ValidationError(u'%s (%s)' % (_(u'username already exists'), data))
      else:
          user = User.objects.create(username=data)
          return user

The idea is that in the POST data, comes a user username that I have to create in my system, along with its profile. Then I created a serialicer profile and the username treated it in the to_internal_value to be created and returned. This I think is not right, but I do not know how to do it correctly.

I guess I would have to create a serializer to create a User and then have it pass to the field username of ProfileSerializer , but I'm not sure how to do it.

Any ideas?

Thank you very much.

    
asked by Juan Alvarez 04.07.2018 в 11:15
source

0 answers