Django rest framework assign POST data to specific user
<p>Started Django and DRF a month ago and I'm stuck on this part... I get a JSON from Android device that already contains a primary key of user so the data gets saved to correct user. Recently I have implemented JWT token authentication (from Blimp) and it's working like a charm. Now I want to remove that primary key field in JSON (sent from Android) and assign data to that logged in user (on Android). Here's some code:</p>

<p>models.py</p>

<pre><code>class Izdavatelji(models.Model):
    user = models.ForeignKey(User, default=1)
    name = models.CharField(max_length=100)

class Obrazac(models.Model):
    izdavatelj = models.ForeignKey(Izdavatelji, default='Izdavatelj')
    local = models.CharField(max_length=100)
</code></pre>

<p>serializers.py</p>

<pre><code>class ObrazacSerializer(serializers.ModelSerializer):      
      class Meta:
            model = Obrazac
            fields = ('local', 'izdavatelj')
</code></pre>

<p>DRF views.py</p>

<pre><code>class ObrazacList(generics.ListCreateAPIView):
    queryset = Obrazac.objects.all()
    serializer_class = ObrazacSerialize
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication,)
</code></pre>

<pre><code>class ObrazacSerializer(serializers.ModelSerializer):   
      izdavatelj = serializers.PrimaryKeyRelatedField(read_only=True)
      class Meta:
            model = Obrazac
            fields = ('local', 'izdavatelj')

class ObrazacList(generics.ListCreateAPIView):
    queryset = Obrazac.objects.all()
    serializer_class = ObrazacSerializer
    permission_classes = (IsAuthenticated,)
    authentication_classes = (JSONWebTokenAuthentication,)

    def perform_create(self, serializer):
        izdavatelj = Izdavatelji.objects.get(user=self.request.user)
        return serializer.save(izdavatelj=izdavatelj)
</code></pre>

<p>Adding a field to <code>serializes.py</code> that pointed to the model relationships and overwriting the <code>perform_create(self, serializer)</code>method in ListCreateAPIView seems to do the job.</p>

python django authentication django-rest-framework jwt