Essex
Essex

Reputation: 6138

Django API REST Framework : Generate a string based on CreateAPIView

I'm looking to use Django API REST Framework in my web application but I get an issue in my project.

In my application, I fill a Django form in order to register a new person in my database.

My model looks like :

class Individu(models.Model):

    NumeroIdentification = models.CharField(max_length=30, null=True, verbose_name='Numero Identification physique', unique=True)
    Civilite = models.CharField(max_length=12,choices=CHOIX_TITRE, verbose_name='Civilité')
    NomJeuneFille = models.CharField(max_length=30, verbose_name='Nom de jeune fille', blank=True)
    Nom = models.CharField(max_length=30, verbose_name='Nom de famille')
    Prenom = models.CharField(max_length=30, verbose_name='Prénom(s)')
    Sexe = models.CharField(max_length=30, choices=CHOIX_SEXE, verbose_name='Sexe')
    Statut = models.CharField(max_length=30, choices=CHOIX_STATUT, verbose_name="Statut civil")
    DateNaissance = models.DateField(verbose_name='Date de naissance')
    VilleNaissance = models.CharField(max_length=30, verbose_name='Ville de naissance')
    PaysNaissance = CountryField(blank_label='Sélectionner un pays', verbose_name='Pays de naissance')
    ...

The field NumeroIdentification is Null but when I submit my form and I am redirected to the next template, I have this function :

def Identity_Individu_Resume(request, id) :

    personne = get_object_or_404(Individu, pk=id)

    obj = Individu.objects.filter (
                                        Prenom=personne.Prenom, 
                                        Nom=personne.Nom, 
                                        DateNaissance=personne.DateNaissance, 
                                        VilleNaissance=personne.VilleNaissance
                                        )

    if obj:
        sc_obj = obj[0] #check if multiple objects are there, means obj[1]

        #Man = 1 / Woman = 2
        sex_number = []
        if personne.Sexe == 'Masculin' :
            sex_number = 1
        else :
            sex_number = 2

        #Get birthday
        birthyear_temp = str(personne.DateNaissance.year)
        birthyear_temp2 = str(birthyear_temp.split(" "))
        birthyear = birthyear_temp2[4] + birthyear_temp2[5]

        #Get birthmonth
        birthmonth_temp = personne.DateNaissance.month
        if len(str(birthmonth_temp)) == 1 :
            birthmonth = '0' + str(birthmonth_temp)
        else :
            birthmonth = birthmonth_temp

        #Get birthcity
        birth_city = personne.VilleNaissance

        #Get random number :
        key_temp = randint(0,999999)
        if len(str(key_temp)) == 1 :
            key = '00000' + str(key_temp)
        elif len(str(key_temp)) == 2 :
            key = '0000' + str(key_temp)
        elif len(str(key_temp)) == 3 :
            key = '000' + str(key_temp)
        elif len(str(key_temp)) == 4 :
            key = '00' + str(key_temp)
        elif len(str(key_temp)) == 5 :
            key = '0' + str(key_temp)
        else :
            key = key_temp

        NumeroIdentification = str(sex_number) + str(birthyear) + str(birthmonth) + str(birth_city) + '-' + str(key)

        #Update NumeroIdentification
        personne.NumeroIdentification = NumeroIdentification

Now I'm trying to implement this function in my API REST.

I have a file named serializer.py :

class IndividuCreateSerializer(serializers.ModelSerializer) :
    class Meta :
        model = Individu
        fields = [
            #'id',
            #'NumeroIdentification',
            'Civilite',
            'Nom',
            'Prenom',
            'Sexe',
            'Statut',
            'DateNaissance',
            'VilleNaissance',
            'PaysNaissance',
            'Nationalite1',
            'Nationalite2',
            'Profession',
            'Adresse',
            'Ville',
            'Zip',
            'Pays',
            'Mail',
            'Telephone',
            #'Creation',
            #'InformationsInstitution',
            #'Utilisateur',
            'Etat',
            #'Image',
            #'CarteIdentite',
        ]

And api.views.py file :

from rest_framework.generics import (
    CreateAPIView,
    UpdateAPIView,
    DestroyAPIView,
    ListAPIView, 
    RetrieveAPIView,
    )


from Identity.models import Individu
from .serializers import IndividuSerializer, IndividuCreateSerializer

class IndividuListAPIView(ListAPIView) :
    queryset = Individu.objects.all()
    serializer_class = IndividuSerializer

class IndividuCreateAPIView(CreateAPIView) :
    queryset = Individu.objects.all()
    serializer_class = IndividuCreateSerializer

class IndividuDetailAPIView(RetrieveAPIView):
    queryset = Individu.objects.all()
    serializer_class = IndividuSerializer

class IndividuUpdateAPIView(UpdateAPIView) :
    queryset = Individu.objects.all()
    serializer_class = IndividuSerializer

class IndividuDeleteAPIView(DestroyAPIView) :
    queryset = Individu.objects.all()
    serializer_class = IndividuSerializer

How I can add the part about NumeroIdentification Generator in my API (Identity_Individu_Resume in my software) ?

Upvotes: 0

Views: 579

Answers (2)

user8060120
user8060120

Reputation:

you can try to use serializermethodfield

class IndividuCreateSerializer(serializers.ModelSerializer) :
    NumeroIdentification = serializers.SerializerMethodField()

    def get_NumeroIdentification(self, obj):
        request = request = self.context.get('request')
        return Individu_Resume(request, obj.id)

Upvotes: 1

neverwalkaloner
neverwalkaloner

Reputation: 47374

You can override create method of IndividuCreateSerializer for this:

class IndividuCreateSerializer(serializers.ModelSerializer):
    ...
    def create(self, validated_data):
        obj = Individu.objects.create(**validated_data)
        Identity_Individu_Resume(obj)
        return obj

note that in my example you will passs Individu object to Identity_Individu_Resume function directly without request so you need to make some modification on Identity_Individu_Resume function.

Upvotes: 2

Related Questions