Django形式有多个模型实例

时间:2017-09-19 14:23:41

标签: python django forms

我正在创建一个Django应用程序,从一个页面我可以添加8个图像(有8个输入字段,其中一个是帖子的主要图像)到博客文章。我有这两个型号:

.git

以下表格:

class Pictures(models.Model):
    file_path = models.ImageField(upload_to='posts/', null=True)
    post = models.ForeignKey(BlogPost, on_delete=models.CASCADE, null=True)

class BlogPost(models.Model):
    title = models.CharField(max_length=100)

我可以轻松创建一个不同形式的帖子做这样的事情:

class CratePostForm(forms.Form):
    title = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control'}))

class CreatePicturesPostForm(forms.Form):
    main_image = forms.FileField()
    image_1 = forms.FileField(required=False)
    image_2 = forms.FileField(required=False)
    image_3 = forms.FileField(required=False)
    image_4 = forms.FileField(required=False)
    image_5 = forms.FileField(required=False)
    image_6 = forms.FileField(required=False)
    image_7 = forms.FileField(required=False)

并将每个图像保存为具有Post的外键的新Picture对象。当我想创建表单的编辑页面时,问题就出现了,我必须在表单中加载以前上传的图像并将其显示给用户。

我想做类似以下的事情:

pictures_form = CreatePicturesPostForm(request.POST, request.FILES)

但是这个实例应该是一个单独的对象,而我有很多来自同一模型的Pictures对象实例。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我强烈建议您在这种情况下使用Django Extra Views。 Link

在您的forms.py中:

from extra_views import InlineFormSet


class PicturesInline(InlineFormSet):

        model = Pictures
        extra = 1
        max_num = 8
        fields = ('file_path',)

class BlogPostForm(forms.ModelForm):

    class Meta:
        model = BlogPost
        fields = ('title', )

在你的views.py中:

from extra_views import CreateWithInlinesView, UpdateWithInlinesView

class BlogPostCreateView(CreateWithInlinesView):
    template_name = ''
    model = BlogPost
    form_class = BlogPostForm
    inlines = [PicturesInline, ]
    success_url = ''

class BlogPostUpdateView(UpdateWithInlinesView):
    template_name = ''
    model = BlogPost
    form_class = BlogPostForm
    inlines = [PicturesInline, ]
    success_url = ''