Search code examples
djangodjango-modelsdjango-formsmany-to-many

Unable to create a many to many field for a new form in Django


models.py-

class B(models.Model):
  filename = models.FileField(upload_to='files/')
  user = models.ForeignKey(User)
class A(models.Model):
  file = models.ManyToManyField(B, blank=True)

forms.py

class AForm(forms.ModelForm):
    file = forms.FileField(label='Select a file to upload', widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False)
    class Meta:
        model = A
        fields = '__all__'

views.py-

if request.method == 'POST':
        a = A()
        form = AForm(request.POST, request.FILES, instance=a)
        if form.is_valid():
            a = form.save(commit=False)
            files = request.FILES.getlist('file')
            for f in files:
                fmodel = B(filename=f, user=request.user)
                fmodel.save()
                a.file.add(fmodel)
            a.save()

This is generating a 505 Error with the server logs showing it as a OSError with the error being at fmodel.save(). I think A expects model B to be already there- not sure how to implement it though. Super new to this stuff.


Solution

  • You must save instance of A before you add instances of B:

    if request.method == 'POST':
        a = A()
        form = AForm(request.POST, request.FILES, instance=a)
        if form.is_valid():
            a = form.save(commit=False)
            a.save()
            files = request.FILES.getlist('file')
            for f in files:
                fmodel = B(filename=f, user=request.user)
                fmodel.save()
                a.file.add(fmodel)