简体   繁体   中英

Django Rest API : Add current User to User Field with Token Auth

Requirements :

Python 3.7
Django 2.0

I'm working on my Django Rest API and I would like to add current user into my User field when an object is created but it doesn't work up to know.

I'm using JWT Authentification with my API Rest.

I followed this question : How to set current user to user field in Django Rest Framework?

But it doesn't seem to work with my code.

I have my serializers.py file :

class IndividuCreateSerializer(serializers.ModelSerializer) :

    class Meta :
        model = Individu
        fields = [
            'Etat',
            'Civilite',
            'Nom',
            'Prenom',
            'Sexe',
            'Statut',
            'DateNaissance',
            'VilleNaissance',
            'PaysNaissance',
            'Nationalite1',
            'Nationalite2',
            'Profession',
            'Adresse',
            'Ville',
            'Zip',
            'Pays',
            'Mail',
            'Telephone',
            'Utilisateur',
            'Image',
            'CarteIdentite',
            ]

    def create(self, validated_data):
       obj = Individu.objects.create(**validated_data)
       Identity_Individu_Resume(self.context.get('request'), obj.id)
       return obj

And my /Api/views.py file :

class IndividuCreateAPIView(CreateAPIView) :

   permission_classes = (IsAuthenticated,)
   authentication_classes = (JSONWebTokenAuthentication,)
   queryset = Individu.objects.all()
   serializer_class = IndividuCreateSerializer

   def user_create(self,serializer):
      serializer.validated_data['Utilisateur'] = self.request.user
      return super(IndividuCreateAPIView, self).user_create(serializer)

In order to try my API, I configured a pythonic file which makes the same job than an other web application.

This file looks like :

import requests

mytoken = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6IkFkbWluIiwiZXhwIjoxNTE5Mzc4MDExLCJlbWFpbCI6InZhbGVudGluQGRhdGFzeXN0ZW1zLmZyIiwib3JpZ19pYXQiOjE1MTkzNzQ0MTF9.7AKpbNEcdir2FLU064QzwwZGiylV-P7LBm1nOJIekwE"
url = 'http://localhost:8000/Api/Identification/create/'

filename1 = '/Users/valentin/Desktop/Django/DatasystemsCORE/Media/pictures/photo.jpg'
filename2 = '/Users/valentin/Desktop/Django/DatasystemsCORE/Media/Carte_Identite/carte_ID.gif'
files = {'Image' : open(filename1,'rb'), 'CarteIdentite': open(filename2,'rb')}

data = {
    "Etat": "Vivant",
    "Civilite": "Monsieur",
    "Nom": "creation",
    "Prenom": "via-api",
    "Sexe": "Masculin",
    "Statut": "Célibataire",
    "DateNaissance": "1991-11-23",
    "VilleNaissance": "STRASBOURG",
    "PaysNaissance": "FR",
    "Nationalite1": "FRANCAISE",
    "Nationalite2": "",
    "Profession": "JJJ",
    "Adresse": "12, rue des fleurs",
    "Ville": "STRASBOURG",
    "Zip": 67000,
    "Pays": "FR",
    "Mail": "",
    "Telephone": ""
    }

response = requests.post(url, files=files, data=data, headers={'Authorization': 'JWT {}'.format(mytoken)})

print(response.text)

My object is well-created but my User field is empty. How I could write this in order to add Current User into the User Field ?

Thank you !

You can pass current user directly to serializer's save method inside view:

class IndividuCreateAPIView(CreateAPIView) :

   permission_classes = (IsAuthenticated,)
   authentication_classes = (JSONWebTokenAuthentication,)
   queryset = Individu.objects.all()
   serializer_class = IndividuCreateSerializer

   def perform_create(self,serializer):
      serializer.save(Utilisateur=self.request.user)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM