A I
A I

Reputation: 381

Model with more than one ForeignKey, ForeignKey can be more than one for one Model

So to make the above possible I have found out that I have to have ManytoMany Field that is not a problem.

That field is in the form as follows:

class Form(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['notes', 'scan']
    widgets = {
        'scan': forms.CheckboxSelectMultiple(),
    }

In the view I have this then:

form = Form(request.POST)
if from.is_valid():
    inst = from.save(commit=False)
    inst.something = something
    inst.save()

Now what do I do, to save the test or scan from the form?

I tried :

inst.test.add(form.cleaned_data['test'])

But that doesn't work for test or scan.

The Model looks like this:

class MyModel(models.Model):
    id = models.AutoField(primary_key=True)
    notes = models.TextField(default='')
    scan = models.ManyToManyField(Scan)
    ....

Please help I wasn't able find anything in the Internet about this Thanks!

Upvotes: 0

Views: 41

Answers (1)

dirkgroten
dirkgroten

Reputation: 20672

The documentation of the Form's save method tells it all: If you have a ModelForm that contains the model's ManyToManyField like this:

class MyForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['__all__']  # or fields = ['scans'] assuming scans is the M2M field in MyModel

Then you have two ways to save the relationships:

  • Directly, using form.save()

Calling save_m2m() is only required if you use save(commit=False). When you use a simple save() on a form, all data – including many-to-many data – is saved without the need for any additional method calls.

  • Or indirectly because you want to manipulate the instance before saving:

    if form.is_valid():
        instance = form.save(commit=False)
        instance.some_field = some_value
        instance.save()
        form.save_m2m()  # this saves the relationships
    

Upvotes: 1

Related Questions