models.py
class UserProfile(models.Model):
contact_no = models.CharField(max_length=20, name='contact_no')
token_key = models.CharField(max_length=128, blank=True, null=True)
user = models.OneToOneField(User, on_delete=models.CASCADE)
role = models.CharField(max_length=128, blank=True, null=True, name='role')
class Meta:
db_table = 'user_profile'
serializers.py
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('id', 'first_name', 'last_name', 'email', 'password',)
extra_kwargs = {'password': {'write_only': True}}
class UserProfileSerializer(serializers.ModelSerializer):
user = UserSerializer(required=True)
class Meta:
model = UserProfile
fields = ('user', 'contact_no', 'role',)
def create(self, validated_data):
"""
Overriding the default create method of the Model serializer.
:param validated_data: data containing all the details of profile
:return: returns a successfully created profile record
"""
user_data = validated_data.pop('user')
user = UserSerializer.create(UserSerializer(),validated_data=user_data)
profile, created = UserProfile.objects.update_or_create(user=user, contact_no=validated_data.pop('contact_no'),
role=validated_data.pop('role'))
return profile
views.py
class UserRecordsView(APIView):
"""
A class based view for creating and fetching profile records
"""
def get(self, request):
"""
Get all the student records
:param format: Format of the profile records to return to
:return: Returns a list of profile records
"""
profiles = UserProfile.objects.all()
serializer_context = {
'request': request,
}
serializer = UserProfileSerializer(profiles, many=True, context=serializer_context)
return Response(serializer.data)
def post(self, request):
"""
:User and User Profile Creation .
:param request:
:return:
"""
serializer = UserProfileSerializer(data=request.data)
if serializer.is_valid(raise_exception=ValueError):
serializer.create(validated_data=request.data)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.error_messages,
status=status.HTTP_400_BAD_REQUEST)
Здесь пароль в виде текста, я хочуЗашифрованная форма пароля. Здесь существует однозначное отношение между таблицей user и userprofile. Я хочу создавать данные user и userprofile только одним способом, поэтому мне нужно шифровать пароль также одновременно.