在django中保存带有表单的几张图像

时间:2017-05-21 12:43:41

标签: python django python-3.x django-1.10

什么是在django中保存多张图片的最佳方式?

我有description个模式,包含2个字段:imageclass Article(models.Model): description = models.TextField(_('Description')) class Image(models.Model): article= models.ForeignKey(Article, on_delete=models.CASCADE) image = models.FileField(_('Image'), upload_to='images/%Y/%m/%d/') 。我尝试了下一个代码,但我的当前表单允许用户只上传一个图像文件。我需要用户可以创建包含多个图像的文章的表单。

也许有人可以提供好的示例或应用程序。我会非常感谢任何帮助。

models.py:

class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ('description', )

    images = MultiFileField()

    def save(self, commit=True):
        instance = super(ArticleForm, self).save(commit)
        for each in self.cleaned_data['images']:
            Image.objects.create(image=each, article=instance)
        return instance

forms.py:

def article_add(request):
    data = dict()
    if request.method == 'POST':
        article_form = ArticleForm(request.POST, request.FILES)
        if article_form.is_valid():
            article = article_form.save(commit=False)
            ******
            article.save()
            data['form_is_valid'] = True
            articles = Article.objects.all
            context = {'articles': articles}
            context.update(csrf(request))
            data['html_article'] = render_to_string('project/article_list.html', context)
        else:
            data['form_is_valid'] = False
    else:
        article_form = ArticleForm()
    context = {'article_form': article_form}
    data['html_article_form'] = render_to_string('project/article_add.html', context, request=request)
    return JsonResponse(data)

views.py:

{% load widget_tweaks %}

<form method="post" action="{% url 'article_add' %}" class="article-add-form dropzone">
    {% csrf_token %}

    {% for field in article_form %}
    <div class="form-group{% if field.errors %} has-danger{% endif %}">
       <label class="form-control-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
       {% render_field field class="form-control" %}
       {% for error in field.errors %}
          <div class="form-control-feedback">{{ error }}</div>
       {% endfor %}
    </div>
    {% endfor %}

    <button type="submit">Submit</button>
</form>

article_add.html:

{{1}}

1 个答案:

答案 0 :(得分:1)

如果你想为一篇文章提供多个图片,也许你可以使用django multi-upload,click here for the docs ..

此外,您可能需要为图像创建单独的模型并将其与文章模型相关联。

class Image(models.Model):
    image = models.FileField()
    article = models.ForeignKey(Article)

关于表格的其余部分在文档中。 此外,从文章模型中删除图像字段。 Django-MultiUpload显示了如何使用单个表单上传多个图像。

Formsets也很有帮助, see here..

修改

在html中将 enctype =&#34; multipart / form-data&#34; 添加到您的表单

<form method="post" action="{% url 'article_add' %}" class="article-add-form dropzone" enctype="multipart/form-data">