N
N
nurzhannogerbek2017-05-22 07:24:24
Django
nurzhannogerbek, 2017-05-22 07:24:24

How to save multiple files (images) at the same time?

Hello! Please help me figure it out.
I'm trying to create a form where the user can create an article by uploading several images into the image field at once. Found the django-multiupload application , which gives you the ability to upload multiple files in one field at the same time. After selecting images, I press the submit button, but under the image field, a message is displayed: Field is empty and field is required. Why is this message displayed if the image field is not empty?
Are there any good ready-made solutions (applications) for uploading multiple files (images) through one field at the same time?
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" enctype="multipart/form-data" 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>

JS:
$(function () {
    var loadForm = function () {
        var btn = $(this);
        $.ajax({
            url: btn.attr("data-url"),
            type: 'get',
            dataType: 'json',
            beforeSend: function () {
                $("#modal").modal("show");
            },
            success: function (data) {
                $("#modal .modal-content").html(data.html_article_form);
            }
        });
    };

    var saveForm = function () {
        var form = $(this);
        var dataForm = new FormData(form);
        $.ajax({
            url: form.attr("action"),
            data: form.serialize(),
            type: form.attr("method"),
            dataType: 'json',
            success: function (data) {
                if (dataForm.form_is_valid) {
                    $("#article-list").html(data.html_article);
                    $("#modal").modal("hide");
                }
                else {
                    $("#modal .modal-content").html(data.html_article_form);
                }
            }
        });
        return false;
    };

    // Create Article
    $("#article-add-button").click(loadForm);
    $("#modal").on("submit", ".js-article-add-form", saveForm);

    // Update Article
    $("#article-list").on("click", "#js-edit-article-button", loadForm);
    $("#modal").on("submit", ".js-article-edit-form", saveForm);
});

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question