Answer the question
In order to leave comments, you need to log in
Uploading files in Django?
modelka
class Attachment(models.Model):
...
file = models.FileField(
upload_to='/media',
verbose_name='File'
)
...
<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>
@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))
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 = []
[<InMemoryUploadedFile: file.txt (text/plain)>, ...]
from the last POST Answer the question
In order to leave comments, you need to log in
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 questionAsk a Question
731 491 924 answers to any question