Home > Enterprise >  updating an object related to two others by a foreignKey and OneToOneKey respectively does not work
updating an object related to two others by a foreignKey and OneToOneKey respectively does not work

Time:09-20

Here is the model of object I want to update:

class Abonnement(models.Model):
    client = models.ForeignKey('Client', on_delete=models.CASCADE, related_name="abonnements")
    compteur = models.OneToOneField(Compteur, on_delete=models.CASCADE,related_name="abonnement")
    adresse = models.CharField(max_length=200, blank=True, null=True)
    point_service = models.CharField(max_length=200, null=True, blank=True)
    lat_machine = models.FloatField(default=0.0)
    lon_machine = models.FloatField(default=0.0)

The Client model is linked to this model by a Foreign key and the Compteur model by a OneToOne key
Retrieving the object from the OneToOne field does not pose a problem. But when I try to update, it does not work.
This is what I do in the controller:

compteur = get_object_or_404(Compteur,pk=request.POST["deveui"])
a = compteur.abonnement
a.point_service = form.cleaned_data["pointservice"]
a.lat_machine = form.cleaned_data["latitude"]
a.lon_machine = form.cleaned_data["latitude"]
a.save()

I also try to do it another way, but nothing changes, the edit still doesn't work

compteur = get_object_or_404(Machine,pk=request.POST["deveui"])
a = Abonnement.objects.get(compteur=compteur)
a.point_service = form.cleaned_data["pointservice"]
a.lat_machine = form.cleaned_data["latitude"]
a.lon_machine = form.cleaned_data["latitude"]
a.save()

CodePudding user response:

It could be that your form.cleaned_data does not contain the values you expect it to, because some validation fails (See the documentation: "If your data does not validate, the cleaned_data dictionary contains only the valid fields" – https://docs.djangoproject.com/en/4.1/ref/forms/api/).

Also, it seems strange that you assign the same value ("latitude") to both a.lat_machine and a.lon_machine.

Finally, try to get error log from the server when you submit the form. If you are using Django'd development server, you should be able to see the errors in the terminal from which you are running the server.

  • Related