I am a beginner with Django and especially with the Django REST framework. Inside "UserRegistration" class, I want to create a new user and ExtendUser using "UserSerializer". how can I do that?
this is my models.py
class ExtendUser(models.Model):
user = models.OneToOneField(User, related_name='user_name', on_delete=models.CASCADE)
address = models.CharField(max_length=300)
phone = models.CharField(max_length=16)
picture = models.ImageField(upload_to='userImages/', default="default.webp", blank=True)
def __str__(self):
return str(self.user)
this is my serializers.py
class UserSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(write_only=True, style={'input_type':'password'})
class Meta:
model = User
fields = ['email', 'first_name', 'password', 'password2']
extra_kwargs = {'password' : {'write_only':True,}}
def save(self):
name = self.validated_data['first_name']
password = self.validated_data['password']
password2 = self.validated_data['password2']
if len(password) < 8:
raise serializers.ValidationError({'error':'Password must be 8-16 Characters '
'and contain both numbers and letters/special character.'})
if password != password2:
raise serializers.ValidationError({'Password':'Password and Confirm Password Should be Same!'})
email = self.validated_data['email']
if User.objects.filter(email=email).exists() == True:
raise serializers.ValidationError({'E-mail': f"{email} this email already been used. Try another email."})
user = User.objects.create_user(username=email, email=email, password=password, first_name=name)
return user
class ExtendUserSerializer(serializers.ModelSerializer):
class Meta:
model = ExtendUser
fields = '__all__'
this is my views.py
class UserRegistration(APIView):
def post(self, request):
user = UserSerializer(data=self.request.data)
if user.is_valid(raise_exception=True):
user.save()
refreshToken = RefreshToken.for_user(user)
context = {'access': str(refreshToken.access_token),
'refresh': str(refreshToken)}
return Response(context, status=status.HTTP_201_CREATED)
return Response(user.errors, status=status.HTTP_400_BAD_REQUEST)
CodePudding user response:
in your case:
class ExtendUser(User):
...
and:
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = ExtendUser
Django made o2o-foreign self.
But it is not really correct, it is better to override default User Model https://docs.djangoproject.com/en/dev/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project
CodePudding user response:
class ExtendUserSerializer(serializers.ModelSerializer):
password2 = serializers.CharField(write_only=True, style=
{'input_type':'password'})
password1 = serializers.CharField(write_only=True, style=
{'input_type':'password'})
email = serialzier.CharField()
first_name = serialzier.CharField()
class Meta:
model = ExtendUser
fields = ['email','password1','password2','first_name','address','phone','picture']
Your Views,py
Firstly we create user and proceed to extend user
class UserRegistration(CreateAPIView):
def perform_create(self, serializer):
data = serialzier.validated_data
password_1 = data.pop('password1')
password_2 = data.pop('password2')
email = data.pop('email')
first_name = data.pop('first_name')
user = User.objects.create(email = email,first_name = first_name)
user.set_password(password_1)
user.save()
ExtendUser.objects.create(user=user,**data)
refreshToken = RefreshToken.for_user(user)
context = {'access': str(refreshToken.access_token),
'refresh': str(refreshToken)}
return Response(context, status=status.HTTP_201_CREATED)
return Response(user.errors, status=status.HTTP_400_BAD_REQUEST)
You can do further validation with Validate Function Please have try once if this solution works
please let me know if you got any error