Django 表单向导 - 为相关 post 模型使用图像表单集

Django Form Wizard - Using an image formset for a related post model

所以我正在使用 Django 表单向导拆分一个简化的 Post表单。在其中一个步骤中,访问者可以上传与 Post.

相关的不同图像

在 SessionWizardView 的 done 方法中,我首先保存实例,然后检查表单集中的图像。

但是我收到以下错误消息;

save() prohibited to prevent data loss due to unsaved related object

我尝试为表单集设置相关的 Post id,但我在这里遗漏了一些东西,表单集仍然是我无法真正理解的东西。感谢任何帮助!

models.py

class Post(models.Model)
    title = models.CharField(max_length=200)
    description = models.TextField(max_length=1000)

    def __str__(self):
        return self.title 

class Image(models.Model):
    post = models.ForeignKey('Post', on_delete=models.SET_NULL, null=True)
    file = models.ImageField(upload_to='images/', null=True, blank=True)
    alt = models.CharField(max_length=200, blank=True)

views.py

FORMS = [
    ('title', PostCreateForm),
    ('image', ImageFormset)
]

TEMPLATES = {
    'title': 'post_form_title.html',
    'image': 'post_form_image.html'
}

class PostWizardView(SessionWizardView):
    form_list = FORMS
    file_storage = FileSystemStorage(location=os.path.join(settings.MEDIA_ROOT, 'temp/'))

    def get_template_names(self):
        return [TEMPLATES[self.steps.current]]

    def done(self, form_list, form_dict, **kwargs):
        instance = Post()

        for form in form_list:
            instance = construct_instance(form, instance)
        instance.save() 
        post_id = instance.pk

        if 'image' in form_dict:
            formset = form_dict['image']
            if formset.is_valid():
                formset.save(commit=False)
                for form in formset:
                    form.post = post_id
                    formset.save()

forms.py

class PostCreateForm(forms.ModelForm):

    class Meta:
        model = Image 
        fields = '__all__'

ImageFormset = inlineformset_factory(
    Post,
    Image,
    form = PostCreateForm,
    min_num=1,
    can_delete=True
)

您应该在循环浏览各个表单时保存它们:

if formset.is_valid():
    for form in formset:
        if form.is_valid():
            f = form.save(commit=False)
            f.post = post_id
            f.save()