Hi everyone, hope you’re having a good day !
My name is Alexis and im having trouble with a modelformset_factory.
i will try to explain as much as i can.
Context: I have two models involved in this case, linked by a ManyToMany relationship declared in the GfcRecette model via num_dossier = models.ManyToManyField(Dossier):
class Dossier(models.Model):
num_dossier = models.AutoField(primary_key=True)
statut = models.ForeignKey(Statut, on_delete=models.CASCADE, default=1)
actif = models.BooleanField(max_length=100, default=1)
...
class GfcRecette(models.Model):
ANNEES = [(str(a), str(a)) for a in range(2010, date.today().year + 1)]
id_gfc_recette = models.AutoField(primary_key=True)
num_dossier = models.ManyToManyField(Dossier)
libelle_facture = models.CharField(max_length=300)
...
Here’s how i declare my formset in my view :
GfcFormset = modelformset_factory(
GfcRecette,
form=GfcRecetteForm,
extra=1,
exclude=['num_dossier']
)
Im using JS to add more forms in my formset (it duplicate my first form and adjust fields id’s)
My page that allows creating or modifying one of these forms is the same.
When I POST my Dossier and GfcRecette forms for the first time, everything works.
When I’m on the page with an existing dossier ID, the Dossier and GfcFormset forms instantiate correctly and appear as expected.
If I modify an element of the Dossier form and POST the modification, it works.
If I add an empty form to the GfcFormset, it adds successfully.
If I add a form to the GfcFormset with data, it adds, but no data is present, and the error is displayed:
- id_gfc_recette
- This field is required.
- id_gfc_recette
- This field is required.
As a reminder, the field “id_gfc_recette” is the primary key of the GfcRecette model. It seems like it should be managed automatically by Django, so I don’t understand why it is lost and requested by the form."
I tried to print primary keys of my GfcForms (forms in my formset) when i access my view :
- When i access my view with instancied forms, primary keys are existing and are printed
- When i access my view with instancied forms, i modify something in any of my formset and POST it, i can see in logs, all my primary keys are none. Then page load again and these Pk’s appears.
It looks like POSTing is making them disapear. I am lost …
Thx for reading me,
Alexis