I was extending User model of django auth table and implementing rest api for the same.
I'm not getting how to implement GET/POST request for the same.
My models.py code is:
class UserProfile(models.Model):
"""User profile model for information about user."""
users = models.OneToOneField(User)
phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999999999'")
phone_number = models.CharField(max_length=100, validators=[phone_regex], blank=True)
created_timestamp = models.DateTimeField(auto_now_add=True, null=True)
updated_timestamp = models.DateTimeField(auto_now=True, null=True)
My serializers.py code is:
class UserSerializer(serializers.ModelSerializer):
"""Serializer for users."""
class Meta:
model = User
class UserProfileSerializer(serializers.ModelSerializer):
"""Serializer for user profiles."""
users = UserSerializer(many=True)
class Meta:
model = UserProfile
def create(self, validated_data):
users_data = validated_data.pop('users')
print 'yes'
print users_data
user_profile = UserProfile.objects.create(**validated_data)
for user_data in users_data:
user_data, created = User.objects.get_or_create(first_name=user_data['first_name'], last_name=user_data['last_name'],
username=user_data['username'], password=user_data['password'], email=user_data['email'], is_active=['is_active'])
user_profile.users.add(user_data)
return user_profile
My v1.py code is :
class UserProfileList(APIView):
"""Get and post user profiles data."""
def get(self, request, format=None):
"""Get users."""
user_profiles = UserProfile.objects.all()
serialized_user_profiles = UserProfileSerializer(user_profiles, many=True)
return Response(serialized_user_profiles.data)
def post(self, request, format=None):
"""Post users."""
serializer = UserSerializer(data=request.data)
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)
I think the problem is in v1.py file. I want to make GET and POST request, for POST request I want to send JSON data. Can someone help me out in its implementation. Actually, I want single endpoint for making POST request and storing data in both User model and UserProfile model.