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已经存在 - 不知道如何实现它。超级新东西。
答案 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)