如何在django中正确保存多个文件?

时间:2017-05-22 04:13:02

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

我需要用户可以创建包含多个图像的文章的表单。我对image字段使用django-multiupload app。我可以选择几张图片但是当我尝试提交表单时,我在图片字段下面有消息:"Field is empty and field is required"。我的错误在哪里?当图像字段不为空时,为什么我会收到此消息?

也许有人可以建议好的示例或应用程序来保存多个图像。我会非常感谢任何帮助。

models.py:

class 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/')

forms.py:

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

    image = MultiFileField()

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

views.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)

article_add.html:

{% load widget_tweaks %}

<form method="post" action="{% url 'article_add' %}" class="article-add-form">
    {% 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>

1 个答案:

答案 0 :(得分:0)

尝试添加&#34; min_num&#34;对图像区域的约束,

image = MultiMediaField(min_num=1, media_type='image')

修改

def article_add(request):
    if request.method == 'POST':
        article_form = ArticleForm(request.POST, request.FILES)
        if article_form.is_valid():
            article = article_form.save(commit=False)
            ******
            article.save()
            #assume you have already a view in the name 'article_list'.
            return redirect('article_list')
    else:
        article_form = ArticleForm()
    context = dict(article_form=article_form)
    return render(request, 'project/article_add.html', context)

问题可能是因为你试图在一个视图中渲染两个模板,同样在使用django模板渲染渲染是一个快捷函数时,最常使用它,而不是字符串转换和解析成json。

另外,&#39; article_list&#39;必须是另一个视图,它显示所有文章的列表,在添加新文章后,您应该考虑重定向到列表视图。在这里,您尝试在单个视图中呈现多个模板。你可以在列表视图中做出类似的事情,

def article_list(request):
    articles = Article.objects.all()
    context = dict(articles=articles)
    return render(request, 'project/article_list.html', context)

虽然,这些是我个人对您刚刚分享的代码的看法。尝试这种方法......