0

Whats the best way to save several images in django?

I have Article modal with 2 fields: description and image. I tried next code but my currect form allows user to upload only one image file. I need form where user can create article with several images.

Maybe someone can advice good examples or apps. I would be very grateful for any help.

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', )

    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

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 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>
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193
  • what you need is a formset. Also, you might have to specify the `user` as a foreign key to this model. That way, multiple of these images can be stored. – karthikr May 21 '17 at 12:50
  • I also thought about formset but as I understand in formset I need to for each image file a separate field. I need to load images by one field. Do you have any ideas? Maybe some usefull apps? – Nurzhan Nogerbek May 21 '17 at 17:57

1 Answers1

1

If you want to have several images for a single article, maybe you could use django multi-upload, click here for the docs..

Also, you may need to create separate model for Images and associate it to the Article model.

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

The rest about the forms are in the docs. Also, remove the image field from the Article model. Django-MultiUpload shows how multiple images can be uploaded using a single form.

OR

Formsets can also be helpful, see here..

EDIT

Add enctype="multipart/form-data" to your form in html

<form method="post" action="{% url 'article_add' %}" class="article-add-form dropzone" enctype="multipart/form-data">
zaidfazil
  • 9,017
  • 2
  • 24
  • 47
  • Thank you for this links. I have some questions about `django-multiupload` app. Check my post again pls. I have form with image field. Now after using this app I can load several images but when I submit form it raise error as "Image field is required" and clean the field. Where is my mistake? The second question: Is it possible to use the same form for edit article. Lets say I want in the future update article information (remove old or add new image). – Nurzhan Nogerbek May 21 '17 at 17:46
  • I dont understand you. What you mean my friend?! =) – Nurzhan Nogerbek May 21 '17 at 17:55
  • sorry man... I was thinking about something else... For the clarification, if you need more help, then post another question with what you've done with .. And again it can be done => editing article and uploading images. but it'd be better to post another question, rather than asking it here... – zaidfazil May 21 '17 at 17:58
  • are you satisfied with the answer? – zaidfazil May 21 '17 at 18:09
  • Well I dont think thats its good idea to ask the same question again. It will be duplicated. It sad of course but anyway thanks to you... – Nurzhan Nogerbek May 21 '17 at 18:12
  • In the post you can see my currect code. Currect template code. Its not error. I have message in template that the image field is empty and image field is required. But I select images so I dont understand why i have such message under the field. `{% for error in field.errors %}` – Nurzhan Nogerbek May 21 '17 at 18:16
  • I did it few minutes ago but it didnt help. I still have that message under `image` field. Do you have any ideas? – Nurzhan Nogerbek May 22 '17 at 04:54