我是Django的新手,我正在寻找有关如何解决此问题的最佳解决方法。
我有这3个模型:
class Rigs(models.Model):
name = models.CharField(max_length=30)
featured_img = models.ImageField(upload_to='images/')
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.name
class Gallery(models.Model):
rigs = models.ForeignKey(Rigs, on_delete=models.CASCADE, related_name='galleries')
file = models.ImageField(upload_to='images/')
def __str__(self):
return self.name
class Specs(models.Model):
cpu = models.CharField(max_length=50)
motherboard = models.CharField(max_length=50)
rigs = models.ForeignKey(Rigs, on_delete=models.CASCADE)
def __str__(self):
return self.cpu
我正在使用该库进行图像的多载(https://github.com/Chive/django-multiupload),因此基本上我构造了 Forms ,类似于文档中所述:
class SpecsForm(forms.ModelForm):
class Meta:
model = Specs
fields = ('rigs', 'motherboard')
class RigForm(forms.ModelForm):
class Meta:
model = Rigs
fields = ('name','featured_img')
gallery_image = MultiMediaField(
min_num=1,
max_num=3,
max_file_size=1024*1024*5,
media_type='image'
)
def save(self, commit=True):
instance = super(RigForm, self).save(commit)
for each in self.cleaned_data['gallery_image']:
Gallery.objects.create(file=each, rigs=instance)
return instance
以及我的视图:
class newrig(CreateView):
model = Rigs
form_class = RigForm
template_name = 'flexrigapp/newrig.html'
success_url = '?success'
我的问题是我不知道如何在HTML表单中包括SpecsForm以及如何使用正确的外键将其保存在数据库中。
我已经尝试通过一些更改将其转移到我的视图中,但是仍然没有效果。
def save(self, commit=True):
instance = super(RigForm, self).save(commit)
for each in self.cleaned_data['gallery_image']:
Gallery.objects.create(file=each, rigs=instance)
return instance
我还尝试了基于函数的视图而不是基于类的视图,但是问题是多重上传验证不适用于我的这种方法,或者我的代码不正确。
预期结果是,应使用“规格和图库”上的适当外键将数据保存在其各自的数据库(钻机,规格,图库)中。现在,我只能保存装备和画廊。
顺便说一下,这是Django 2.2.4。
更新
我尝试将视图更新为基于函数的视图,就像@dirkgroten建议的那样。
def newrig(request):
if request.method == 'POST':
rig_form = RigForm(request.POST, request.FILES, prefix="rigs")
specs_form = SpecsForm(request.POST, prefix="specs")
if rig_form.is_valid() and specs_form.is_valid():
rigs = rig_form.save()
specs = specs_form.save(commit=False)
specs.rigs = rigs
specs.save()
return HttpResponseRedirect("?success")
else:
rig_form = RigForm(prefix="rigs")
specs_form = SpecsForm(prefix="specs")
return render(request, "flexrigapp/newrig.html", {'rig_form': rig_form,'specs_form': specs_form,})
现在没有数据被保存在数据库中。没有错误日志。