无法为Django中的新表单创建多对多字段

时间:2018-04-18 15:13:25

标签: django django-models django-forms many-to-many

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()

生成505错误,服务器日志将其显示为OSError,错误为fmodel.save()。我认为A期望模型B已经存在 - 不知道如何实现它。超级新东西。

1 个答案:

答案 0 :(得分:2)

在添加A的实例之前,您必须保存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)