[resolved] data, forms and models

Hello everyone.

I’m searching for long hours about how to add data on model, by forms. Let me explain :


def ajout_chantier(request):
url = "https://api-adresse.data.gouv.fr/search/?q="
plus = '+'

form = ChantiersForm() # my model

if request.method == 'POST':
    #print('Printing POST:', request.POST)
    form = ChantiersForm(request.POST)

    if form.is_valid():
            ville = form.cleaned_data.get('ville')
            cp = form.cleaned_data.get('code_postal')
            adresse = form.cleaned_data.get('adresse')
            ville.replace("", "+")
            cp.replace("", "+")
            fin_url = "&limit=1"
            test = url + adresse.replace(" ", "+") + plus + ville.replace(" ", "+") + plus + cp + fin_url
            content = requests.get(test)
            data = content.json()

                i_ville = data['features'][0]['properties']['city']
                i_ville2 = ''.join((c for c in unicodedata.normalize('NFD', i_ville) if unicodedata.category(c) != 'Mn'))
                i_cp = data['features'][0]['properties']['postcode']
                i_adr = data['features'][0]['properties']['name']
                lat = data['features'][0]['geometry']['coordinates'][1] # this script gives the latitude from adress, city code and city
                lon = data['features'][0]['geometry']['coordinates'][0] # this script gives longitude from adress, city code and city
                if (i_ville2.lower().replace("-", " ") == ville.lower() and i_cp == cp):
                    print("latitude : ",lat, "longitude : ",lon)
                    print("Voici la requete : ", test)
                    print(form.cleaned_data.get('nom'), form.cleaned_data.get('ville'), form.cleaned_data.get('code_postal'))
                    ident = form.cleaned_data.get('id')
                    name = form.cleaned_data.get('nom')

                    b_update = Chantiers.objects.filter(id=ident, nom=name).update(lon = lon, lat = lat) # lon & lat are in my model Chantiers, but i've not put them on forms
                    print("Les villes et cp ne correspondent pas.")
                    print("Voici la requete : ", test)

            except IndexError:
                print("Les variables n'existent pas, veuillez recommencer.")

    return redirect('/')
context = {'form':form}
return render(request, 'membres/ajout_chantier.html', context)`

I would like to save all the data from forms, and to fill up variables lat and lon which are calculated by the small script i’ve wrote. There is an issue because when i submit, all data is good except lat & lon variables, which are blank.

The best solution i’ve found to now makes an another issue : it duplicates the data and in my model, lon & lat are missing; but in the other one all things are missing except lon & lat.

I hope you will help me,

Best regards.