I am making a web site for a travel agency. I am using a modal field FileField to add PDF files to more pages.

models.py

class Travel(models.Model):
    docfile = models.FileField(upload_to='documents')

It works fine when uploading just one file in admin and displaying one file on the template.

file.html

<div>
    <h4><a href="{{ travel.docfile.url }}">{{ travel.docfile.name }}</a></h4>
</div>

But what if I want to upload and display more than one file per page? I now I could loop over all files to get all files for all pages:

{% if documents %}
    <ul>
    {% for document in documents %}
        <li><a href="{{ document.docfile.url }}">{{ document.docfile.name }}</a></li>
    {% endfor %}
    </ul>
{% else %}
    <p>No documents.</p>
{% endif %}

view.py

def vacation(request):
    if request.method == 'POST':
        form = DocumentForm(request.POST, request.FILES)
        if form.is_valid():
            newdoc = Travel(docfile = request.FILES['docfile'])
            newdoc.save()

            return HttpResponseRedirect(reverse('myapp.views.vacation'))
    else:
        form = DocumentForm()

    documents = Travel.objects.all()

    return render_to_response('myapp/file.html',{'documents': documents, 'form': form},context_instance=RequestContext(request))

But how can I upload and display more files for one page?

Thank you for your time.

score:0

there are a few ways (that I can see):

  1. you allow up to N uploads each time: thus you just create a form with N fields to take care of it. It's not very fancy (nor the most usable UI), but it's easy to implement.

  2. if you want to give the user the possibility to upload a "dynamic" number of files, you may implement a view that is called via ajax. This still requires your user to select one file at the time, and load it, but then you can upload several files one after the other, without reload the entire page. You may even find some reusable app, like the following, that already should implement the most of it: https://github.com/skoczen/django-ajax-uploader

  3. you can use the HTML5 multiple attribute of the <input type="file" ... field. Even in this case there is an interesting reusable app: https://github.com/Chive/django-multiupload

Hope it helps


Related Query