2016-06-04 3 views
0

Profile 모델은 user에 의해 OneToOne 필드에 연결되어 있습니다. 프로필과 사용자를 연결하기 위해 프로필 작성 프로세스를 어떻게 변경할 수 있습니까? 토큰 인증을 사용합니다. 당신이 현재 loggedin 사용자를 저장하려면Django Rest Framework - 기존 사용자 모델 확장 및 저장

class ProfileCreateSerializer(ModelSerializer): 
    class Meta: 
      model = Profile 
      fields = [ 
       'name', 
       'age', 
       'heigth', 
       'location', 
      ] 

class ProfileCreateAPIView(CreateAPIView): 
    queryset = Profile.objects.all() 
    serializer_class = ProfileCreateSerializer 
+0

현재 사용자에게 'user.user'가 할당되어 있습니까? 즉 request.user입니까? –

+0

나는 그것이 일할 수 있다고 생각한다. 내가 request.user에서 사용자를 얻고 프로필의 사용자 필드에 전달해야합니까? –

답변

1

, 당신은 ProfileCreateAPIViewperform_create() 방법을 대체 할 수 있습니다.

이 방법에서는 user 인수를 값이 request.user으로 전달할 수 있습니다. DRF는이 추가 값을 serializer에 정의 된 필드와 함께 사용하여 Profile 인스턴스를 만듭니다.

class ProfileCreateAPIView(CreateAPIView): 
    queryset = Profile.objects.all() 
    serializer_class = ProfileCreateSerializer 

    def perform_create(self, serializer):   
     serializer.save(user=self.request.user) # pass the user field 
+0

잘 작동합니다! 고마워요! –

관련 문제