This is my register_user func in views.py, as title suggests I cant register a profile bec of user_id not null constarint. I am beginner to the framework
@api_view(['POST'])
def register_user(request):
with transaction.atomic():
user_serializer = UserSerializer(data=request.data)
if user_serializer.is_valid():
new_user = user_serializer.save()
print(new_user.id)
profile_data = {
'user': new_user.id, # Pass user ID to the profile serializer
'first_name': request.data.get('first_name', ''),
'last_name': request.data.get('last_name', ''),
'email': request.data.get('email', '')
}
profile_serializer = ProfileSerializer(data=profile_data)
try:
if profile_serializer.is_valid():
print("profile")
profile_serializer.save()
return Response(user_serializer.data, status=status.HTTP_201_CREATED)
else:
new_user.delete() # Delete user if profile creation fails
return Response(profile_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
except IntegrityError as e:
print(f"Integrity Error: {e}") # Print the integrity error
new_user.delete() # Delete user to avoid inconsistent data
return Response({'error': str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
return Response(user_serializer.errors, status=status.HTTP_400_BAD_REQUEST)
this are my serializers in serializers.py:
from rest_framework import serializers
from base.models import *
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['username', 'password', 'email']
extra_kwargs = {'password': {'write_only': True}}
def create(self, validated_data):
user = User.objects.create_user(**validated_data)
return user
class ProfileSerializer(serializers.ModelSerializer):
user = UserSerializer(many=False, read_only=True)
class Meta:
model = Profile
fields = ('user', 'first_name', 'last_name', 'email')
and this is the Profile Model:
from django.db import models
from django.contrib.auth.models import User
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
first_name = models.CharField(max_length=100)
last_name = models.CharField(max_length=100)
email = models.EmailField()
class Meta:
app_label = 'base'
def __str__(self):
return self.user.username
I’d appreciate it if you can point me out to the error i been using the react form to post a new user and debugging for nearly an hour but got to nothing.