How to connect many to many relationaship if I save them via form.save() (django)?

Viewed 27

This link https://docs.djangoproject.com/en/3.2/topics/db/examples/many_to_many/ explains that I need to make an object of the class to save the connection. Because I have many fields in my classes I used form.save() to save them, but that doesn't fill the connection ManyToMany in the class. How to fill that field?

def create(response):
    if response.method == "POST":
        if "next" in response.POST:
            form = CreateNewPerson(response.POST)
            form.save()
            form2 = CreateNewDog() # form doesn't have filed many_to_many to Person, but class Dog does


class CreateNewDog(forms.ModelForm):
    class Meta:
        model = Dog
        fields = ['name','years_old', 'sex', 'blood_type', 'image']


class Dog(models.Model):
    owner =  models.ForeignKey(Person, on_delete=models.SET_NULL, null=True)
    user = models.ManyToManyField(User)

1 Answers

You can save the form, get the instance, and manage the relation like this:

def create(request):
    if request.method == "POST":
        if "next" in request.POST:
            form = CreateNewPerson(request.POST)
            person = form.save() # get the person

            form2 = CreateNewDog(request.POST)
            dog = form2.save() # get the dog
            dog.user.add(person) # assign the person to the dog

Note that response was changed to request.

Related