V
V
Vyacheslav Rakhinsky2016-07-23 13:11:07
Django
Vyacheslav Rakhinsky, 2016-07-23 13:11:07

Uploading files in Django?

modelka

class Attachment(models.Model):
...
    file = models.FileField(
        upload_to='/media',
        verbose_name='File'
    )
...

The form
<form class="..." method="POST" id="..." enctype="multipart/form-data">
    {% csrf_token %}
    <div class="...">
        <button class="...">Upload files</button>
        <input type="file" name="files" id="files" multiple>
    </div>

    <div class="...">
        <button class="..." type="submit" form="...">Create</button>
    </div>
</form>

view
@csrf_protect
@login_required
def EditView(request,pk=None):

    if request.method == 'POST':
        try:
            ...
            for f in request.FILES.getlist('files'):
                post.attachments.append(f)

            post.full_clean()
            post.save()

            return redirect('/app/posts/' + str(post.id) + '/#comments')

        except ValidationError as e:
            ...

    context.update({
        'self': request.user,
        'post': post,
        'errors': errors,
        'messages': messages.get_messages(request)
    })

    return render_to_response('app/posts/edit.html', context, context_instance=RequestContext(request))

And a piece of the model in which the save is in progress
class Post(models.Model):
    ...
    attachments = []

    def save(self, *args, **kwargs):
        super(Post, self).save(*args, **kwargs)

        if len(self.attachments) > 0:
            from .attachment import Attachment
            for attachment in self.attachments:
                a = Attachment(post=self.pk, file=attachment, original=str(attachment))
                a.full_clean()
                a.save()
        self.attachments = []

Well, now the question is for the connoisseurs
. Attachment is not a required field
. When saving, if there are files, they are saved, everything is fine.
But if you then make another POST without attachments, the error "I / O operation on closed file."
It turns out that in request.FILES there is
[<InMemoryUploadedFile: file.txt (text/plain)>, ...]
from the last POST
How to remove them from there and where?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vyacheslav Rakhinsky, 2016-07-23
@rakhinskiy

You just had to drink coffee)
It turns out that if you set self.attachments = [] to zero in def save(), then this is not enough
. You should have added it to the view

self.attachments = []
for f in request.FILES.getlist('files'):
    post.attachments.append(f)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question